donturner
donturner

Reputation: 19176

How can I vary the return type of an overridden method?

How can I enforce that all Cars should have Tyres of a specific type? I am using Java 1.3 (for mobile) so unable to use generics.

abstract class Car{

    private Tyre[] tyres;

    protected Car(){
        tyres = createTyres();
    }

    protected abstract Tyre[] createTyres(); 

    public Tyre[] getTyres(){
        return tyres;
    }
}

abstract class Tyre{}

//Concrete classes
class SlickTyre extends Tyre{}

class RacingCar extends Car {
    public RacingCar(){
    }
    protected SlickTyre[] createTyres(){
        return new SlickTyre[]{};
    }
    public SlickTyre[] getTyres(){
        //this won't compile as it overrides the parent return type     
    }

Upvotes: 0

Views: 124

Answers (2)

d-enabled
d-enabled

Reputation: 11

If SlickTyre has extra properties/functions then other Tyre, you might have broke the LSP principle.

If you are working on J2ME (you mentioned mobile), the general practice is to avoid abstraction if not necessary, these extra overhead might impacts on jar size and performance. Well, we practice that 5 years ago when phones requires jar file to be less than 64kb.

Upvotes: 1

amit
amit

Reputation: 178521

Unfortunately, covariant return type was added to java only from java5. Older version [such as 1.3] require no variance return type.

You can read more about it in this article

Upvotes: 2

Related Questions