In the HourlyEmployee and SalariedEmployee sub-classes we call super()
to pass "name" to the base class constructor. I have two questions:
Where does the variable name come from, is this a typo for the aName variable?
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);
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With