java - 静态方法重载错误

标签 java oop inheritance static overloading

我认为我的重载(或覆盖)有问题。每次我使用我创建的驱动程序类进行调用时,它都会返回(“无法从 Doctor 类型对非静态方法 Duty(int) 进行静态引用”)。通过 Doctor 对象调用 Duty 方法时,如何使用它。

博士类

public class Doctor extends Employee {
    private int patientsSeen;

    public Doctor(int patientsSeen) {
        super(150000,45);
        this.patientsSeen = patientsSeen;

    }

    public void duty(int patientsSeen) {
        if(patientsSeen < 0) {
            System.out.println("Another Patient goes home happy!");
            this.patientsSeen = patientsSeen;
            System.out.println(patientsSeen + " patients sent home happy!");
        }
        else
            System.out.println("Patients are waiting, get back to work!");  

    }
    public String toString() {
        super.toString();
        return patientsSeen + " ";
    }


}

驱动程序

public class Driver {

    public static void main(String[] args) {
        Employee doctor = new Doctor(0);
        Employee surgeon = new Surgeon(0);
        Janitor janitor = new Janitor(0);

        Janitor.duty(0);
        Doctor.duty(0);

    }

}

最佳答案

Janitor 是您类(class)的名称。 janitorJanitor 类实例的名称。

当您尝试调用特定于您的实例的方法时,您需要引用您的实例看门人而不是您的类Janitor

您正在寻找的是:

janitor.duty(0);

doctor.duty(0);

您是否使用过:

Janitor.duty(0);

Doctor.duty(0);

你会这样称呼:

public static void duty(int patientsSeen) { ... }

关于java - 静态方法重载错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29614766/

相关文章:

java.lang.StringIndexOutOfBoundsException : String index out of range: -1 (Works with another program)

java - 使用数组矩阵RGB java将图像转换为灰度

java - 访问父类(super class)的私有(private)成员

c++ - 有人可以告诉我的代码有什么问题吗?

java - 是否有可能摆脱 Spring Data JPA Repository 中的@Param Annotation

java - 是否可以回调多个监听器?

oop - 如何设计业务逻辑层

python - 如果我使用与父类(super class)相同的名称,我是否会覆盖子类方法中的父类(super class)定义?

javascript将对象方法传递给不同的对象方法

java - 从父类(super class)构造函数调用基类覆盖的方法