在引用从对象数组中打印的方法时,找不到符号错误

时间:2013-04-12 11:12:26

标签: java compiler-errors

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

  

无法找到方法getTeamSize()位置等级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();
}

1 个答案:

答案 0 :(得分:0)

我认为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(), " ");
}