Inheritance and fields Suppose that we want to give lawyers a 5000 raise for

# Inheritance and fields suppose that we want to give

• Notes
• 102

This preview shows page 39 - 47 out of 102 pages.

Inheritance and fields Suppose that we want to give lawyers a \$5000 raise for each year they've been with the company. The following modification doesn't work: public class Lawyer extends Employee { public Lawyer(int years) { super(years); } public double getSalary() { return super.getSalary() + 5000 * years; } } The error is the following: Lawyer.java:7: years has private access in Employee return super.getSalary() + 5000 * years; ^
Improved Employee code Add an accessor for any field needed by the superclass. public class Employee { private int years; public Employee(int years) { this.years = years; } public int getYears() { return years; } } public class Lawyer extends Employee { public Lawyer(int years) { super(years); } public double getSalary() { return super.getSalary() + 5000 * getYears() ; } }
Revisiting Secretary The Secretary class currently has a poor solution. We set all Secretaries to 0 years because they do not get a vacation bonus for their service. If we call getYears on a Secretary object, we'll always get 0. This isn't a good solution; what if we wanted to give some other reward to all employees based on years of service? Let's redesign our Employee class a bit to allow for a better solution. 42
Improved Employee code Let's separate the standard 10 vacation days from those that are awarded based on seniority. public class Employee { private int years; public Employee(int years) { this.years = years; } public int getVacationDays() { return 10 + getSeniorityBonus() ; } // vacation days given for each year in the company public int getSeniorityBonus() { return 2 * years; } ... } How does this help us improve Secretary ?
.