Java - 22 多态数组

wxrwajiez / 2024-10-19 / 原文

Java - 22 多态数组+多态参数

多态数组

数组的定义类型为父类类型,里面保存的实际元素为子类类型

Person[] persons = new Person[5];
person[0] = new Person("Jack", 20);
person[1] = new Student("Rose", 18, 100);
person[2] = new Teacher("LiHua", 30, 2000);

for(int i = 0; i<persons.length; i++){
    /* person[i].study();
       person[i].teach(); 不能直接使用,因为study和teach方法是student类和teacher类独有的 */
    // 正确使用方法
    if(person[i] instanceof Student){
        Student student = (Student)person[i];
        student.study();
	}
    if(person[i] instanceof Teacher){
        Teacher teacher = (Teacher)teacher[i];
        teacher.teach();
        //  ((Teacher)teacher[i]).teach();
	}
    
}

多态参数

方法定义的形参类型为父类类型,实参类型为子类类型