簡體   English   中英

如何使用子類中的屬性而不是擴展抽象類中的屬性?

[英]How to use an attribute in the subclass and not the one from the extended abstract class?

我希望你在這個子類中使用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 +"$";

    }
}

public void setSalary(double salary) {
    this.salary = rate*hours;
}

您正在乘以您在超類中設置的默認值,但不使用參數。

問題是您在調用 setter 方法之前正在打印值。 嘗試先調用它,然后進行toString調用。

  1. 使用構造函數創建 HourlyEmployee 對象,
  2. 調用對象的 setSalary 方法,
  3. 現在, toString 方法應該返回正確的值

第一次,父類的salary屬性在創建子類實例時總是調用的父類構造函數中的0值初始化,所以需要在創建子類實例后立即調用setSalary方法進行修正薪水屬性的值以及在您的下一個代碼中使用它之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM