I have the following classes:
public class Base {
public int someMethod(){...}
}
public class Derrived extends Base {
@Override
public int someMethod(){...}
}
Also I have a method that return the List<Base>
List<Base> method() {
return fetch();
}
Method fetch() returns List<? extends Base> but actually it holds list of instances of Derrived class
List<? extends Base> fetch() {}
But code that defines method method() will not compile. It requires casting to List<Base>. Why I need cast it if I always can treat to instances of that collection as instances of Base class?
A
List<? extends Base>isn’t the same thing as aList<Base>, in the same way that a bunch of bananas isn’t a fruitbowl.Consider:
It’s one thing to treat all existing elements of a
List<Derived>as instances ofBase– but you can’t add aBaseto aList<Base>, whereas you can add one to aList<Derived>. There not everyList<Derived>isList<Base>.