Java Reference
In-Depth Information
As you'll see, inheritance hierarchies are commonly used in Java to group related
classes of objects and reuse code between them.
Extending a Class
The previous section presented a nonprogramming example of hierarchies. But as an
exercise, we could write small Java classes to represent those categories of employees.
The code will be a bit silly but will illustrate some important concepts.
Let's imagine that we have the following rules for our employees:
Employees work 40 hours per week.
All employees earn a salary of $40,000 per year, with the exception of mar-
keters, who make $50,000 per year, and legal secretaries, who make $45,000 per
year.
Employees have two weeks of paid vacation leave per year, with the exception
of lawyers, who have three weeks of vacation leave.
Employees use a yellow form to apply for vacation leave, with the exception of
lawyers, who use a special pink form.
Each type of employee has unique behavior: Lawyers know how to handle law-
suits, marketers know how to advertise, secretaries know how to take dictation,
and legal secretaries know how to file legal briefs.
Let's write a class to represent the common behavior of all employees. (Think of
this as the 20-page employee manual.) We'll write methods called getHours ,
getSalary , getVacationDays ,and getVacationForm to represent these behav-
iors. To keep things simple, each method will just return some value representing the
default employee behavior, such as the $40,000 salary and the yellow form for vaca-
tion leave. We won't declare any fields for now. Here is the code for the basic
Employee class:
1 // A class to represent employees in general.
2 public class Employee {
3 public int getHours() {
4 return 40;
5 }
6
7 public double getSalary() {
8 return 40000.0;
9 }
10
11 public int getVacationDays() {
12 return 10;
13 }
14
 
Search WWH ::




Custom Search