簡體   English   中英

收到“無法對非靜態方法進行靜態引用”錯誤,但我尚未將要從中調用的方法聲明為靜態方法

[英]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()。

DoctorStaff的子類。 當我在代碼中用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM