当父为抽象时,将 ArrayList<Parent> 的类型更改为 ArrayList<Child>

mia*_*cam 4 java casting arraylist abstract

我的问题是我有两个班级:父母和孩子。

父类是abstract,子类从它们扩展而来。

然后我有一个返回父级的方法,ArrayList我需要将它转换 ArrayList为子级。

我该做什么?

Cra*_*Kid 6

您可以通过以下方式进行:

import java.util.ArrayList;
import java.util.List;

    abstract class Parent {
        void callMe(){
            System.out.println("Parent"); 
        } 
    } 
    class Child extends Parent {
        void callMe(){
            System.out.println("Child");
        }
    }
    public class TestClass {
        public static void main(String[] args) {
            List<Parent> alist=new ArrayList<Parent>();
            List<? super Child> alist2=alist;
        }
    }
Run Code Online (Sandbox Code Playgroud)

List<Parent> 与 不同List<Child>。Compilor不允许的参考分配List<Parent>List<Child>即使列表只包含子对象。

例如:

List<Parent>  parentList=new ArryList<Parent>();
parentList.add(new Child());
parentList.add(new Child());
parentList.add(new Child());
//This is not allowed
List<Child>  childList=(List<Child>)parentList;//Compiler Error

//But,This is allowed
List<? super Child>  childList=parentList; //Okey
Run Code Online (Sandbox Code Playgroud)

这是允许的,因为使用List<? super Child>保证List<Parent>不会损坏的参考。