0

当我尝试编译时,出现错误:

无法从 Doctor 类型对非静态方法 getId() 进行静态引用。

Doctor是 的子类Staff。当我在代码中Doctor替换为时,我得到了同样的错误。Staff我知道我不能用超类代替子类,所以这就是为什么Staff不起作用,但是在我的Database类中,我没有将任何东西声明为静态,所以我不明白它为什么或如何是静态的以及为什么我收到了那个错误。

这是我的数据库类

import java.util.ArrayList;


public class Database
{
String id;

private ArrayList<Staff> staff;

/**
 * Construct an empty Database.
 */
public Database()
{
    staff = new ArrayList<Staff>();
}

/**
 * Add an item to the database.
 * @param theItem The item to be added.
 */
public void addStaff(Staff staffMember)
{
    staff.add(staffMember);
}

/**
 * Print a list of all currently stored items to the
 * text terminal.
 */
public void list()
{
    for(Staff s : staff) {
        s.print();
        System.out.println();   // empty line between items
    }
}

public void printStaff()
{
    for(Staff s : staff){


        id = Doctor.getId();//This is where I'm getting the error.


        if(true)
        {
            s.print();
        }
    }
}

这是我的员工课。

public class Staff
{
    private String name;
    private int staffNumber;
    private String office;
    private String id;

/**
 * Initialise the fields of the item.
 * @param theName The name of this member of staff.
 * @param theStaffNumber The number of this member of staff.
 * @param theOffice The office of this member of staff.
 */
public Staff(String staffId, String theName, int theStaffNumber, String theOffice)
{
    id = staffId;
    name = theName;
    staffNumber = theStaffNumber;
    office = theOffice;
}

public String getId()
{
   return this.id;
}


/**
 * Print details about this member of staff to the text terminal.
 */
public void print()
{
    System.out.println("ID: " + id);
    System.out.println("Name: " + name);
    System.out.println("Staff Number: " + staffNumber);
    System.out.println("Office: " + office);

}

}

4

1 回答 1

3

您正在调用该方法,就好像它是静态的一样,因为您使用类名来调用它:Doctor.getId()

You'll need an instance of the class Doctor to call the instance methods.

Perhaps you intend to call getId on the s (instance of Staff) in the loop?

于 2012-10-03T15:55:59.763 回答