Java Reference
In-Depth Information
The next section discusses two more important OO design relationships that you should
adhere to in your Java applications: the is-a and the has-a relationships.
OO Design Relationships
You need to be able to develop code that implements is-a and/or has-a relationships for the
exam. When you design applications, you make decisions as to how your objects are related
to each other. Some objects are extensions of existing objects, making inheritance a good
design choice. Some objects are made up of other objects, in which case composition is the
better design choice.
The is-a relationship is a simple check to verify that you are using inheritance properly.
Specifi cally, you should be able to state that a child object “is a” parent object. The has-a
relationship is a simple check to verify that you are using composition properly. Specifi cally,
if an object “has a” specifi c attribute or property, the attribute or property is a good
candidate for a fi eld within the object's class.
This section discusses the details you need to know regarding the is-a and has-a
relationships, starting with the is-a relationship.
The “is-a” Relationship
In Java, a child class is allowed only one parent and can subclass any other non-fi nal
class. From a design point of view, your inheritance should satisfy the is-a relationship , a
simple test to determine if you are using a proper approach and good code design in your
application regarding inheritance. The test is simple, but the result is very important: you
should be able to state that your child object “is a” parent object.
For example, suppose a class named Cat extends a Pet class. Because a cat “is a” pet, this
inheritance is probably a good design. Figure 6.1 shows what these classes might look like.
A cat is a pet, so Cat extending Pet is a good design.
FIGURE 6.1
Pet
name : String
age : int
eat() : void
Good design: A cat
is a pet.
Cat
breathe() : void
sleep() : void
 
Search WWH ::




Custom Search