【发布时间】: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