public class ProductionWorker extends Employee
{
private int shift;
private double rateOfPay;
private double hoursWorked;
ProductionWorker(String name, int id, int shift, double rateOfPay, double hoursWorked)
{
super(name, id);
this.shift = shift;
this.rateOfPay = rateOfPay;
this.hoursWorked = hoursWorked;
}
public class TeamLeader extends ProductionWorker
{
private double monthlyBonus;
TeamLeader(String name,int id, int shift, double rateOfPay, double hoursWorked, double monthlyBonus)
{
super(name, id , shift, rateOfPay, hoursWorked);
this.monthlyBonus = monthlyBonus;
}
public double calcPay()
{
double pay = 0;
//night shift
if (shift == 2)
{
pay = ((hoursWorked + hoursWorked / 2) * rateOfPay) + monthlyBonus;
}
else
{
pay = (hoursWorked * rateOfPay) + monthlyBonus;
}
return pay;
}
}
我将类ProductionWorker扩展到TeamLeader类,然后在类TeamLeader上创建方法calcPay()我的问题是我需要从类ProductionWorker获取变量shift,hoursOfWorked和rateOfPay的值,以便可以对我使用方法calcPay() main。有人可以帮助我吗,谢谢您。
最佳答案
要访问父类(ProductionWorker)的变量,您需要将变量范围从专用更改为受保护。
私有变量仅在该类中可见。
受保护的变量在子类中和包中的所有类中均可见
您可以参考以下链接:http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html。
如果您不想将它们设置为保护状态,则也可以为变量创建getter和setter,但这不是首选方法。
例如,getter和setter:
private int shift;
protected int getShift() {
return this.shift;
}
protected void setShift(int shift) {
this.shift = shift;
}