In Kathy Sierra's book on SCJP we learn that, When we write
List <A> list = new ArrayList <A> ();
This means that this list will accept elements of type A only, not it's subtype or supertype, only type A. Then I came across this example
import java.util.*;
interface A {
public void a();
}
class B implements A {
public void a() { }
public void b() { }
}
class C extends B {
public void a() { }
}
class D extends C {
}
public class Generics {
public static void main() {
List <B> lst = new ArrayList <B> ();
lst.add(new B());
lst.add(new C());
lst.add(new D());
}
}
Here a list has been declared with B as it's bound type. But it looks like it's accepting objects of it's subtype also. Why is it so? And if it is possible then is this declaration available in java
List <? extends B> list = new ArrayList <B> ();
Now with this notation we tell compiler that any type which extends B is allowed to enter this list. Please help, I am really confused