oshilan
oshilan

Reputation: 23

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>();
    }
}

Upvotes: 0

Views: 50

Answers (1)

JCW
JCW

Reputation: 222

Change line 2 to:

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

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

Upvotes: 1

Related Questions