For example, lets say you have two classes:
public class TestA {}
public class TestB extends TestA{}
I have a method that returns a L
if you have an object of the class TestA
, you can't cast it to TestB
. every TestB
is a TestA
, but not the other way.
in the following code:
TestA a = new TestA();
TestB b = (TestB) a;
the second line would throw a ClassCastException
.
you can only cast a TestA
reference if the object itself is TestB
. for example:
TestA a = new TestB();
TestB b = (TestB) a;
so, you may not always cast a list of TestA
to a list of TestB
.