我已经编写了在 Java 中使用继承和多态的程序,但是遇到了一些问题,请参阅下面的代码:
超类:
public class Worker {
private String name;
private double salaryRate;
public Worker(String nm, double rate){
nm=name;
rate=salaryRate;
}
public void computePay(int hours){
double pay=hours*salaryRate;
System.out.println("The Salary for "+getName()+" is "+pay);
}
public String toString(){
return name+" "+salaryRate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalaryRate() {
return salaryRate;
}
public void setSalaryRate(double salaryRate) {
this.salaryRate = salaryRate;
}
}
一个子类:
public class HourlyWorker extends Worker {
public HourlyWorker(String nm, double rate) {
super(nm, rate);
}
public void computePay(int hours){
if (hours>40){
double extraPay=(hours-40)*1.5*getSalaryRate();
double pay=40*getSalaryRate();
double total=extraPay+pay;
System.out.println("The salary for "+getName()+" is "+total);
}
else{
super.computePay(hours);
}
}
}
另一个子类:
public class SalariedWorker extends Worker {
public SalariedWorker(String nm, double rate){
super(nm,rate);
}
public void computePay(int hours){
double pay=40*getSalaryRate();
System.out.println("The salary for "+getName()+" is "+pay);
}
}
Main() 方法:
public class Test {
public static void main(String[] args) {
Worker a=new HourlyWorker("Tom",2.0);
Worker b=new HourlyWorker("Lee",2.0);
Worker c=new SalariedWorker("Pei",2.0);
Worker d=new SalariedWorker("Joe",2.0);
System.out.println(a+" "+b+" "+c+" "+" "+d);
a.computePay(50);
b.computePay(30);
c.computePay(20);
d.computePay(60);
}
}
有点长,感谢您的耐心阅读:)但是,当他们编译时,它显示:
null 0.0 null 0.0 null 0.0 null 0.0
The salary for null is 0.0
The Salary for null is 0.0
The salary for null is 0.0
The salary for null is 0.0
请问哪里出错了,谢谢大家!