java - 收到 "cannot make a static reference to the non-static method"错误,但我尚未将调用的方法声明为静态

标签 java

当我尝试编译时,出现错误:

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

DoctorStaff 的子类。当我在代码中将 Doctor 替换为 Staff 时,出现同样的错误。我知道我不能用父类(super class)替换子类,所以这就是为什么 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();
        }
    }
}

这是我的员工类(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);

}

}

最佳答案

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

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

也许您打算在循环中的 s(Staff 实例)上调用 getId

关于java - 收到 "cannot make a static reference to the non-static method"错误,但我尚未将调用的方法声明为静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12712234/

相关文章:

java - Scala 高阶函数与提供示例之间的逐步连接

java - 为什么所有内容都从我的数组列表中删除?

java - 手动控制自动化功能

java - 尽管异常,DBunit 仍插入 xml

java - WebSphere : How to retrieve a user's credentials from CAS ticket?

java - DocumentFilter 只允许将数字和句点 (.) 放入 JTextField 中?

java - 以编程方式添加或设置 JAXB XmlRootElement

java - Hadoop CustomInputFormat NullPointerException

java - Codenameone,如何调用或加载android原生进度对话框?

java - 程序执行并无故停止