You cannot cast this, because you would make a promise you cannot hold.
When you cast from List<MyClass>
to List<Interface>
you take a list containing several objects of type MyClass and vast it to a type that makes (among others) the following promises:
Interface get(int index)
- you can get an element of thpe Interface (no problem)
boolean add(Interface e)
- you can add any element of type Interface (if it is a subtype of MyClass or not) (this is a problem!)
The second point is problematic, because the underlying List is still a list of MyClass
and not a list of Interface
in general. You could still hold a link to the underlying List in a separate variable and could run get
on that list. If you added an object of type Interface
, that is not also a MyClass
, you could get this Non-MyClass
from the List<MyClass>
.
As all the other answers and comments have pointed out, the correct solution is the type List<? extends Interface>
. With this type, you can still get objects of type Interface
from the list (as a return value of a method call), but you cannot put anything into the list (use as a parameter of a method call).