我希望您在此子类中使用方法setSalary
,但我不知道如何使用。它会一直打印出我在超类中初始化的默认值。
超类代码:
public abstract class Employee {
private String name;
private String ssn;
protected double salary;
public Employee (String n,String s){
this.name=n;
this.ssn=s;
this.salary=0;
}
public abstract void setSalary(double salary);
@Override
public String toString() {
return "Employee Name: " + name + ", with social security number: " + ssn;
}
}
子类代码:*
public class HourlyEmployee extends Employee {
private int hours;
private int rate;
public HourlyEmployee(int hours, int rate, String n, String s) {
super(n, s);
this.hours = hours;
this.rate = rate;
}
public void setSalary(double salary) {
this.salary = rate*hours;
}
@Override
public String toString() {
return super.toString()+ "\n"+ "Number of working hours is " +hours+ " and the rate per hour is" + rate + "\n"+" Employee salary is: " +salary +"$";
}
}
答案 0 :(得分:0)
在
public void setSalary(double salary) {
this.salary = rate*hours;
}
您要乘以您在超类中设置的默认值,而不使用参数。
答案 1 :(得分:0)
问题是您要在调用setter方法之前打印值。尝试先调用它,然后进行toString
调用。
答案 2 :(得分:0)
答案 3 :(得分:0)
第一次,通过创建子类实例时始终调用的super构造函数中的0值来初始化超类的salary属性,因此在创建的实例之后,需要调用setSalary方法子类来纠正薪水属性的值,并在下一部分代码中使用它之前。