![](/img/trans.png)
[英]Getting error “Cannot make a static reference to the non-static method putExtra(String, String) from the type Intent”
[英]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
當我嘗試編譯時,出現錯誤:
無法從Doctor類型靜態引用非靜態方法getId()。
Doctor
是Staff
的子類。 當我在代碼中用Staff
替換Doctor
時,出現相同的錯誤。 我知道我不能用超類代替子類,這就是為什么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);
}
}
您正在調用該方法,就好像它是靜態的一樣,因為您使用的是類名Doctor.getId()
。
您將需要Doctor
類的實例來調用實例方法。
也許您打算在循環中的s
(Staff實例)上調用getId
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.