1

I have an interface like so:

public interface FruitGetter {
    public Fruit getFruit();
    public List<Fruit> getFruits(int numFruit);
}

Fruit is an interface that I may implement for different types of fruit.

My confusion comes from the fact that implementing the two methods above doesn't seem to be consistent:

@Override
public Apple getFruit(){return new Apple();}

@Override
public List<Apple> getFruits(int numFruit){ //you get the idea}

Can someone please explain why the second implementation is an incompatible return type, while the first method seems to work correctly?

Joe Roddy
  • 729
  • 6
  • 12
  • 1
    The second way doesn't work because `List` isn't a subtype of `List`. – Andy Turner Sep 03 '16 at 21:55
  • 2
    You need a type variable on `FruitGetter`: `FruitGetter`; use `F` in place of `Fruit` in the methods. Then implement it as `class AppleGetter implements FruitGetter`. – Andy Turner Sep 03 '16 at 21:58
  • Java allows for covariant return types. i.e., you can override a method with a return type that is a subtype of the original. Like `Apple` is a subtype of `Fruit`. But like Andy said, the same doesn't go for `List` and `List`. You can see why here: [Link](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p) – Jorn Vernee Sep 03 '16 at 21:58
  • Thank you Andy :D – Joe Roddy Sep 03 '16 at 22:00

0 Answers0