【问题标题】:Static method Overloading Error静态方法重载错误
【发布时间】:2015-04-13 20:45:36
【问题描述】:

我假设我的重载(或覆盖)有问题。每次我使用我创建的驱动程序类调用时,它都会返回(“无法从 Doctor 类型对非静态方法 duty(int) 进行静态引用”)。通过医生对象调用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.duty(0); 和doctor.duty(0);。这些是实例方法,所以你应该通过你创建的对象来调用它们,而不是像你现在所做的那样。
  • @user2336315 您应该将此作为答案发布。
  • @Turing85 它当然应该作为重复的 xxx 关闭,它可能已经存在但懒得找到:)
  • 我将其标记为“简单的印刷错误”来关闭它。在问题中,据说他试图通过医生对象来调用它,这对我来说意味着他知道他需要使用该对象,但没有注意到他使用了大写的 D 而不是小 D。
  • @Aify IMO 这不是一个简单的错字,而是对 ClassName.method 和 instanceName.method 之间区别的巨大误解,否则 OP 不会问这个问题并自己找到他的错字。

标签: java oop inheritance static overloading


【解决方案1】:

Janitor 是您班级的名称。 janitor 是您的类 Janitor 实例的名称。

当您尝试调用特定于您的实例的方法时,您需要引用您的实例管理员而不是您的类管理员。

你要找的是:

janitor.duty(0);

doctor.duty(0);

您是否使用过:

Janitor.duty(0);

Doctor.duty(0);

你会这样称呼:

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

【讨论】:

    【解决方案2】:

    您正在尝试调用类的方法,而不是实例。 应该是:

    janitor.duty(0);
    doctor.duty(0);
    

    【讨论】:

      【解决方案3】:

      您正在尝试将非静态方法“duty(int)”作为静态方法调用。将其更改为:

      janitor.duty(0);
      doctor.duty(0);
      

      并且代码应该可以工作。您必须从 'Doctor' 的实例(或首先实现 'duty' 的超类)或其子类之一调用它们。

      【讨论】:

        【解决方案4】:

        除了所有给出的答案之外,还有一件更重要的事情。从您的代码看来,它既不是覆盖也不是重载。现在注意几点:

        1. 如果您的 Employee 类有一个 non static 和 非私有 duty(int ) 方法,那么在子类 Doctor 中,这将是一个duty(int ) 方法的覆盖版本

        2. 1234563
        3. 现在考虑Employee 类没有duty(int ) 方法。但是在您的Doctor 类中,您有两个带有这些签名的duty() 方法-duty(int ) 和duty(float )。然后在OOP 中说duty() 方法已为int 和float 重载

        【讨论】:

        • 非常感谢您的意见,这是我在这里的第一篇文章,哇,帮助太棒了!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-18
        • 2019-08-31
        • 2018-08-02
        • 2012-09-12
        • 1970-01-01
        相关资源
        最近更新 更多