我已经编写了用于在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


请告知哪里出了问题,谢谢大家!

最佳答案

您的分配在构造函数中相反。您没有使用输入参数设置实例属性值,因此这些属性始终具有默认值。

public Worker(String nm, double rate){
nm=name;
rate=salaryRate;
}




public Worker(String nm, double rate){
   this.name=nm;
   this.salaryRate=rate;
}


注意:如果输入参数的名称和类属性相同,则使用this还可帮助您避免阴影问题。

09-25 21:36