For example, lets say you have two classes:
public class TestA {}
public class TestB extends TestA{}
I have a method that returns a L
You really can't*:
Example is taken from this Java tutorial
Assume there are two types A
and B
such that B extends A
.
Then the following code is correct:
B b = new B();
A a = b;
The previous code is valid because B
is a subclass of A
.
Now, what happens with List
and List
?
It turns out that List
is not a subclass of List
therefore we cannot write
List b = new ArrayList<>();
List a = b; // error, List is not of type List
Furthermore, we can't even write
List b = new ArrayList<>();
List a = (List)b; // error, List is not of type List
*: To make the casting possible we need a common parent for both List
and List
: List>
for example. The following is valid:
List b = new ArrayList<>();
List> t = (List)b;
List a = (List)t;
You will, however, get a warning. You can suppress it by adding @SuppressWarnings("unchecked")
to your method.