父类数组如何向下转型
父类数组里面装的是子类的对象,但是父类数组new的时候new的是父类数组
如下
Person[] people = new Student[]{new Student("田径", 77),new Student("田径", 77)};这个时候Student继承了Person
但是我们该如何转型成为Student数组,直接转换编译是不报错的,但是我想行您能明白运行是什么状况ClassCastException
所以我们该怎么办?
请看下面的方法
private static void change(Person[] people) {
List<Student> list4 = (List) Arrays.asList(people);
//Student[] students = new Student[100];
Student[] students = list4.toArray(new Student[0]);
for(int i = 0 ; i < 2; i ++){
System.out.println(students[i]);
}
}

浙公网安备 33010602011771号