Domanda

In the HourlyEmployee and SalariedEmployee sub-classes we call super() to pass "name" to the base class constructor. I have two questions:

  1. Where does the variable name come from, is this a typo for the aName variable?

  2. How does calling setSalary() work in those sub-classes?

Does extending the Employee class gives us a copy of the setSalary() method but then inside the method there is aSalary=salary; where salary is not inherited because it is private OR does inheritance simply let us use the setSalary() method from the base class which is why using super() to pass the name would make sense.

public class Employee {
  private String name;
  private double salary;

  public Employee(String aName) {
     name = aName; 
  }

  public void setSalary(double aSalary) {
     salary = aSalary; 
  }

  public String getName() {
     return name; 
  }

  public double getSalary() {
     return salary; 
  }

  public double getWeeklySalary() {
     return salary/52; 
  }
}

public class HourlyEmployee extends Employee {
    public HourlyEmployee(String aName, double anHourlySalary) {
        super(name);
        setSalary(anHourlySalary*40*52);
    }
}

public class SalariedEmployee extends Employee {
    public SalariedEmployee(String aName, double anAnnualSalary) {
        super(name);
        setSalary(anAnnualSalary);
    }
}
È stato utile?

Soluzione

  1. Where does the variable name come from, is this a typo for the aName variable ?

    Yes, it's a typo. Should be aName, otherwise it won't compile.

  2. How does calling setSalary() work in those sub-classes ?

    When extending a class, the subclass inherits all of the functionality in the superclass. This is why the SalariedEmployee and HourlyEmployee classes have access to the setSalary() method: they both inherit the functionality from the Employee class.

    You should note that the subclasses don't access the salary field directly, but via the setSalary() and the getSalary() methods. This is called encapsulation and it's used to restrict the direct access to the class members.

Altri suggerimenti

  1. public Employee(String aName) is public, so you can invoke it from extending class
  2. private fields and method are inherited from extended classes, but they are not accesible from it. If you use a debugger you can see that private fields are part of inherited class, but you have no visibility.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top