Oscar Courchaine Oscar Courchaine - 3 months ago 14
Java Question

Cannot return subclasses of abstract class in implementations of an abstract method

I have two sub-classes of an abstract class which each implement an abstract method of their superclass. I want to have a different return type for each, though those return types are in turn sub-classes of a different abstract class. See below:

public abstract class Gardener {

public abstract ArrayList<Flower> getFlowers();
}

public class GardererA extends Gardener {

public ArrayList<Flower> getFlowers() {
return new ArrayList<Daisy>();
}
}

public class GardererB extends Gardener {

public ArrayList<Flower> getFlowers() {
return new ArrayList<Rose>();
}
}

public abstract class Flower {}

public class Daisy extends Flower {}

public class Rose extends Flower {}


Obviously Java won't let me do this, but I'm at a loss for how to get this functionality. Any ideas?

Answer

Use wildcards:

public abstract class Gardener {

    public abstract ArrayList<? extends Flower> getFlowers();

}