【发布时间】:2020-09-25 03:39:14
【问题描述】:
我有一个 Employee 类(包括字段:empId、name、方法:getEmpId、getName、setEmpId、setName)。我从 Employee 创建了一个名为 HourlyEmployee 的继承类。 HourlyEmployee 类有附加字段:rate、hours 和附加方法:setRate、setHours、monthlyPayment。我创建了一个名为 he1 的 HourlyEmployee 对象,当调用 setEmpId 和 setName 时,它会打印 0 和 null。你能告诉我我的代码有什么问题吗?谢谢。
public class Employee {
// instance variables
private int empId;
private String name;
// constructor
public Employee(){
}
public Employee(int empId, String name) {
this.empId = empId;
this.name = name;
}
// get methods
public int getEmpId() {
return empId;
}
public String getName() {
return name;
}
// set methods
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
public static class HourlyEmployee extends Employee {
private int empId;
private String name;
private double rate;
private double hours;
public HourlyEmployee() {
}
public HourlyEmployee (int empId, String name, double rate, double hours) {
this.empId = empId;
this.name = name;
this.rate = rate;
this.hours = hours;
}
public void setRate(double rate) {
this.rate = rate;
}
public void setHours(double hours) {
this.hours = hours;
}
public double monthlyPayment(){
double monthlyPayment = rate * hours;
return monthlyPayment;
}
public void employeeInfo(){
System.out.println("The employee's id is: " + empId);
System.out.println("The employee's name is: " + name);
System.out.println("The hourly rate is: " + rate);
System.out.println("The employee worked " + hours + " for a month");
}
}
public class Test {
public static void main(String[] args) {
int id;
String name;
double rate;
double hours;
double salary;
// create an hourly employee object with no-arg constructor
HourlyEmployee he1 = new HourlyEmployee ();
// set instance variables
he1.setEmpId(1);
he1.setName("Jane");
he1.setRate(15.0);
he1.setHours(50.0);
// display employee info
he1.employeeInfo();
// display monthly payment
System.out.println("Monthly payment, before change, is: " + he1.monthlyPayment());
// change the rate
he1.setRate(22.0);
// display monthly payment
System.out.println("Monthly payment, after change, is: " + he1.monthlyPayment());
【问题讨论】:
-
通过重新声明具有相同名称的字段,您正在创建单独的变量(即使它们具有相同的名称)。不要那样做。不再声明名称和 ID,而是再次将特定值传递给超类中的字段。在构造函数中,您可以通过
super(empId, name);实现它。此外,由于超类型中的这些字段对于 get 是私有的,因此它们的值使用 getter 方法,例如System.out.println("The employee's id is: " + getEmpId());. -
非常感谢。学习 super() 真是太好了。
标签: java class inheritance methods null