Java Reference
In-Depth Information
The is-a Relationship and Polymorphism
The is-a relationship is more than a test to verify good inheritance design. It is also useful
in understating object-oriented programming and polymorphism. For example, using the
Cat and Pet classes from Figure 6.1, the following statement is valid in Java:
Pet c = new Cat();
Why can a Pet reference point to a Cat object? Because a Cat object “is a” Pet object. We
discuss this topic in detail in the upcoming section “Polymorphism.”
The is-a relationship is not unique to Java. Inheritance in any OO programming
language should satisfy the is-a relationship. Now let's look at another design test: the has-
a relationship.
The “has-a” Relationship
Composition refers to a class that contains a reference to another class. The has-a
relationship is a test to decide when a class should use composition. For example, suppose
we have a class called Address that we want to use with an Employee class to represent an
employee's home and mailing addresses. Because an employee “has a” address, composition
is a good design choice. Figure 6.4 illustrates this relationship.
An employee “has a” address, so making Address a field of Employee is a
FIGURE 6.4
good design.
Employee
Adress
home : Address
mailing : Address
street : String
city : String
state : String
zip : int
Good design: An employee has a home
and mailing address.
We saw in the previous section that Employee extending Person is a good design because
an employee is a person. However, inheritance is not a good design with Address and
Employee because an address is not an employee, nor is an employee an address.
Search WWH ::




Custom Search