How do you cast a List of supertypes to a List of subtypes?

前端 未结 17 1306
面向向阳花
面向向阳花 2020-11-22 08:43

For example, lets say you have two classes:

public class TestA {}
public class TestB extends TestA{}

I have a method that returns a L

17条回答
  •  心在旅途
    2020-11-22 08:58

    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.

提交回复
热议问题