[英]getting “cannot make a static reference to the non-static method” error, but I haven't declared the method I'm calling from as static
When I try compile I'm getting the error: 当我尝试编译时,出现错误:
cannot make a static reference to the non-static method getId() from the type Doctor. 无法从Doctor类型静态引用非静态方法getId()。
Doctor
is a sub-class of Staff
. Doctor
是Staff
的子类。 I get the same error when I replace Doctor
with Staff
in the code. 当我在代码中用Staff
替换Doctor
时,出现相同的错误。 I understand that I can't substitute a super-class for a sub-class so that's why Staff
wont work, but in my Database
class, I haven't declared anything as static so I don't understand why or how it is static and why I'm getting that error. 我知道我不能用超类代替子类,这就是为什么Staff
无法正常工作的原因,但是在我的Database
类中,我没有声明任何静态内容,因此我不理解它为什么或如何静态以及为什么我会收到该错误。
This is my database class 这是我的数据库类
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();
}
}
}
This is my Staff class. 这是我的职员班。
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);
}
} }
You're calling the method as if it's static, since you're calling it using the class name: Doctor.getId()
. 您正在调用该方法,就好像它是静态的一样,因为您使用的是类名Doctor.getId()
。
You'll need an instance of the class Doctor
to call the instance methods. 您将需要Doctor
类的实例来调用实例方法。
Perhaps you intend to call getId
on the s
(instance of Staff) in the loop? 也许您打算在循环中的s
(Staff实例)上调用getId
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.