0

I am getting a cannot find symbol error when trying to print out the contents of an array of objects based on istanceof either TeamLeader or Engineer. When i get to the class specific methods the error pops up:

Cannot find method getTeamSize() location class Person.

The getTeamSize is from the TeamLeader subclass. Same error paired with a method from the other subclass specific method.

Errors occur on lines 112 and 117 within the System.out.printf():

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();
}
4

1 回答 1

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(), " ");
}
于 2013-04-12T11:18:56.320 回答