Java Reference
In-Depth Information
Heterogeneous Collections
A
heterogeneous collection
is a collection of objects that are not the same data type but
have a common parent class. Continuing with the
Pet
class example, suppose we defi ne an
ArrayList
of
Pet
references:
ArrayList<Pet> pets = new ArrayList<Pet>();
Any object of type
Pet
can be added to the
pets
collection. For example, the following
statements add three different types of objects to
pets
:
pets.add(new Pet(“”, 4));
pets.add(new Cat(“Alley”, 7));
pets.add(new Dog(“Fido”, 2));
Each statement is valid, and the
ArrayList
now contains one
Pet
object, one
Cat
object,
and one
Dog
object. This type of collection is made possible because of polymorphism.
As far as the
ArrayList
is concerned, the only objects in
pets
are of type
Pet
because the
collection consists of
Pet
references. However, because of polymorphism, the collection
actually contains different types of objects like
Cat
and
Dog
objects.
Summary
This chapter covered the “OO Concepts” objectives of the SCJP exam. The goal of this
chapter was to discuss the details of object-oriented programming and the standard design
rules to follow when you develop OO applications.
We discussed the details of tight encapsulation, loose coupling, and high cohesion. Tight
encapsulation is when you make the fi elds of your class private and only allow access to the
fi eld via public methods. The benefi t of tight encapsulation is that you control the changes
made to your fi elds and also hide from the users the implementation details of the class.
Loose coupling is when you design your objects to minimize the number of dependencies
on other objects. Loose coupling goes hand in hand with tight encapsulation and allows for
changes in a class to have a minimal effect on the other classes it is coupled with.
High cohesion is when you design your objects to perform specifi c, closely related tasks.
A highly cohesive object does a specifi c job and does that job well, without relying on a lot
of input from other objects. High cohesion works hand in hand with loose coupling and
allows for more logical code that is easier to understand.
The two OO design relationships that we discussed were the is-a and has-a
relationships. The is-a relationship is a simple but important test to determine if you are
implementing a good inheritance design. Whenever you use inheritance, you should be able
to state that a child object “is a” parent object. Similarly, the has-a relationship is used to
verify that you are using composition properly. If a class has an object fi eld, you should be
able to state that the class “has a” object as one of its attributes.
Search WWH ::
Custom Search