向下转换不起作用并在我的程序中给出错误

时间:2018-07-25 08:24:01

标签: java polymorphism instanceof downcast

我有一个Person类和一个扩展Person的类讲师

public class Driver {
public static void main(String args[]) {
    Person[] array = new Person[5];
    array[1] = new Person("John Doe");
    array[2] = new Person("Bobby Gram");
    array[3] = new Person("Jeb Too");
    array[4] = new Instructor("Jill Crill", "Computer Science");
    array[5] = new Instructor("Hello World", "Math");

    for(int i = 0; i < array.length; i++) {
        System.out.println(array[i].toString());
    }
    for(int i = 0; i < array.length; i++) {
        int total = 0;
        if (array[i] instanceof Instructor) {
            Person person = (Instructor) array[i];
            person.getSubject();
        }
    }

}
}

    for(int i = 0; i < array.length; i++) {
        int total = 0;
        if (array[i] instanceof Instructor) {
            Person person = (Instructor) array[i];
            person.getSubject();    //error: The method getSubject() is undefined for the type Person
        }
    }

即使我垂头丧气也给我一个错误吗? Instructor类具有getSubject()方法。

1 个答案:

答案 0 :(得分:0)

if (array[i] instanceof Instructor) {
        Instructor person = (Instructor) array[i];
        person.getSubject();
}

由于person是Person类的引用变量,因此即使动态创建的对象是Instructor的实例,也无法识别getSubject()方法。按照上述代码更改代码,这将解决您的问题。