2012-10-03 43 views
0

调用方法时我试图编译我得到的错误:收到“不能让一个静态参考非静态方法”的错误,但我还没有宣布我是从静态

cannot make a static reference to the non-static method getId() from the type Doctor.

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

你能提供'Doctor.getId()'的来源吗?你把它称为“静态”,它是静态的吗? –

+1

减少您的代码示例。几乎所有这些都是无关紧要的。所需要的就是如何定义'getId()'方法以及不能编译的代码行。 (当然,您应该测试缩减的示例以查看错误是否仍然存在。) – millimoose

回答

3

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

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

也许你打算在循环中的s(员工实例)上拨打getId

+0

我已经在循环中的员工实例上调用了getId,它工作正常。谢谢:)它现在打印所有的工作人员(我有两种类型的工作人员 - 医生和护士)。我想要做的只是打印选定类型的工作人员,但我认为我可以自己找出其他问题(我对Java仍然很陌生)。我通过他们的身份证号码的第一位来区分他们。 – user1577173

相关问题