0

コンパイルしようとすると、次のエラーが表示されます。

タイプ Doctor から非静的メソッド getId() への静的参照を作成することはできません。

DoctorのサブクラスですStaff。コードでを置き換える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);

}

}

4

1 に答える 1

3

クラス名を使用して呼び出しているため、静的であるかのようにメソッドを呼び出しています: Doctor.getId()

Doctorインスタンス メソッドを呼び出すには、クラスのインスタンスが必要です。

getIdおそらく、ループ内でs(Staff のインスタンス)を呼び出すつもりですか?

于 2012-10-03T15:55:59.763 に答える