java - 引用从对象数组进行打印的方法时找不到符号错误

尝试根据TeamLeader或Engineer的istance打印出对象数组的内容时,出现了找不到符号错误。当我进入类的特定方法时,错误 pop :

Cannot find method getTeamSize() location class Person.


getTeamSize来自TeamLeader子类。与其他子类特定方法中的方法配对的错误相同。
System.out.printf()中的第112和117行发生错误:
try {
    in = new ObjectInputStream(new FileInputStream("persons.dat"));
    Person[] personList = new Person[3];
    for (int i = 0; i < personList.length; i++) {
        personList[i] = (Person) in.readObject();
    }
    System.out.printf("%-20s %3s %10s %10s", "Name", "Age", "Team Size", "Experience\n");
    for (int x = 0; x < personList.length; x++) {
        if (personList[x] instanceof TeamLeader) {
            System.out.printf("-20s %3i %10i %10s\n",
                              personList[x].getName(), personList[x].getAge(),
                              personList[x].getTeamSize(), " ");
        } else {
            System.out.printf("-20s %3i %10s %10.1f\n",
                              personList[x].getName(), personList[x].getAge(),
                              " ", personList[x].getExperience());
        }

    }
    System.out.println();
} catch (IOException e) {
    System.out.println("Problem reading file");
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    System.out.println("Could not find designated class");
    e.printStackTrace();
}

最佳答案

我想getTeamSize()方法仅存在于TeamLeader类中,而不存在于Person类中。因此,您需要将Person强制转换为TeamLeader才能使用该方法:

if (personList[x] instanceof TeamLeader){
    TeamLeader teamLeader = (TeamLeader) personList[x];
    System.out.printf("-20s %3i %10i %10s\n",
        teamLeader.getName(), teamLeader.getAge(), 
        teamLeader.getTeamSize(), " ");
}

https://stackoverflow.com/questions/15969886/

相关文章:

c++ - qmobilityglobal.h : No such file or director

compiler-errors - ICC无法打开头文件

compilation - Fedora 18 上的内核编译错误(在 Macbook 上的 Virt

actionscript-3 - 如何使用ASC2.0修复Error “A conflict exi

c++ - 使用 Boost.Python 和静态库构建

c++ - 头文件问题

java - 开始Java : Printing out a 5 pointed star usin

xml - 访问AS3中XML对象的可能未定义的属性?

c++ - 在C++中,编译-std = c++ 0x需要什么?

permissions - 为什么即使许可为777,WHMCS在应用其安全提示后仍显示许可错误?