获取“无法对非静态方法进行静态引用”错误,但我还没有将我调用的方法声明为静态

时间:2012-10-03 15:54:23

标签: java

当我尝试编译时,我收到错误:

  

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

DoctorStaff的子类。当我在代码中用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);

}

}

1 个答案:

答案 0 :(得分:3)

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

您需要类Doctor的实例来调用实例方法。

也许您打算在循环中调用getId(人员实例)上的s