Some days ago I was writing a simple Java program, and I discovered that this piece of code doesn't work (it gives a compile-time error):
ArrayList<Document> docs = new ArrayList<Book>();
where Document is an interface and Book implements Document.
Why inheritance in Java doesn't work with generics? If I want that code to work, I must use wildcards, like this:
ArrayList<? extends Document> docs = new ArrayList<Book>();
I was wondering what is the reason of this? If I need an ArrayList of Documents, and I know that a Book is also a Document, why can't I use an ArrayList of Books as an ArrayList of Documents?