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

前端 未结 17 1641
面向向阳花
面向向阳花 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 09:07

    casting of generics is not possible, but if you define the list in another way it is possible to store TestB in it:

    List myList = new ArrayList();
    

    You still have type checking to do when you are using the objects in the list.

提交回复
热议问题