简体   繁体   中英

overriding with different return types (generic collections)

Please help me solve the following:

  1. class Cat must extend Animal (keep inheritance);
  2. Animal.getAll() must return all animals (cats, dogs, etc.) and Cat.getAll() must return only cats (don't alter the signature).

I've tried and failed with error The return type is incompatible with Animal.getAll() on line 8.

class Animal {
    public static List<Animal> getAll() {
        return new ArrayList<Animal>();
    }
}

class Cat extends Animal {
    public static List<Cat> getAll() {
        return new ArrayList<Cat>();
    }
}

Change line 2 to:

public static List<? extends Animal> getAll() {

it will work. See Java Wildcards in Generics for more information

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