简体   繁体   中英

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?

Use wildcards:

public abstract class Gardener {

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

}

You can use generics like this:

public abstract class Gardener<T extends Flower> {

    public abstract ArrayList<T> getFlowers();
}

public class GardererA extends Gardener<Daisy> {

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

public class GardererB extends Gardener<Rose> {

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

public abstract class Flower {}

public class Daisy extends Flower {}

public class Rose extends Flower {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM