zoukankan      html  css  js  c++  java
  • 父类数组如何向下转型

    父类数组里面装的是子类的对象,但是父类数组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]);
            }
    }
    
    
    

      



  • 相关阅读:
    navigator
    历史记录跳转
    更改URL
    计数器
    窗口位置和大小
    open用法
    confirm用法
    项目中访问本地node服务跨域问题
    jenkins使用
    基于Vue的SSR
  • 原文地址:https://www.cnblogs.com/WINDZLY/p/12693198.html
Copyright © 2011-2022 走看看