Simple casting TestClassOne-> TestClassTwo
will not work, unless your testList1
collection holds instances of TestClassTwo
, and only them.
Casting that you want to achieve is impossible, because even though TestClassTwo
extends TestClassOne
, there is no gurantee, that class TestClassTwo
would have a suficient constructor. TestClassTwo
may have additional variables, that JVM would not know what to do with. So as you can see this would be problematic even for humans.
==========================================================================
Casting in other way is possible. Because TestClassTwo
will have same methods as TestClassOne
, because it extends it.
==========================================================================
If you want to hold elements of both TestClassOne
and TestClassTwo
in same collction, then you can use generic wildcards:
List<? extends TestClassOne> testList1 = new ArrayList<>();
But you will have to check if given element is of type TestClassTwo, before casting.
TestClassOne one = testLis.get(1);
if(one instanceOf TestClassTwo.class) {
(TestClassTwo) one; // handle me
}
one; // can't be casted, but can be adapted
==========================================================================
Other solution would be to use an adapter constructor in TestClassTwo
. It will accept TestClassOne
as an argument (and optionaly insert additional parameters, if needed). The creation of TestClassTwo
objects should be managed by you.
class TestClassTwo extends TestClassOne{
TestClassTwo(TestClassOne in) {...}
}
Then you can use simply adapt:
List<TestClassOne> testList1 = new ArrayList<>();//add some arguments
List<TestClassTwo> testList2 = testList1.stream().map(TestClassTwo::new).collect(toList());