Java Reference
In-Depth Information
Suppose I need to write a class to represent employees of a company. Because the Pet
class contains fi elds like name and age , I might be tempted to write an Employee class that
extends Pet to reuse the code in Pet , as Figure 6.2 shows.
FIGURE 6.2
Good inheritance design needs to satisfy the “is a” relationship.
Pet
name : String
age : int
eat() : void
Poor design: An employee
is not a pet.
Employee
salary : double
work() : void
Although this design might work functionally and allow me to store an employee's name
and age in the fi elds of Pet , the design is not a good one because an employee is not a pet.
A better design is for the Employee class to extend a class like Person , because most
likely an employee “is a” person. Figure 6.3 shows what these classes might look like.
FIGURE 6.3
An employee is a person, so Employee extending Person is a good design.
Person
name : String
age : int
Good design: An employee
is a person.
Employee
salary : double
work() : void
 
Search WWH ::




Custom Search