Java Reference
In-Depth Information
The reuse mechanism is quite simple and straightforward, but design-
ing systems based on object composition requires a new way of thinking.
Suppose there is a system that contains a class named Rectangle, and that
the Rectangle class contains a public method named area() that calcu-
lates the area of a rectangular figure. Now assume that you need to create
a class named Window, and that the objects of Window are rectangular in
shape. If an object of Window needed to calculate its area it could con-
sider using the method area() in rectangle.
One possible approach is through inheritance; that is, you could make
Window extend Rectangle. Since Rectangle is the superclass and Window
the subclass, an object of Window can access the area() method in rectan-
gle. The problem with this inheritance-based approach to class reuse is
that it assumes that a Window “is a kind-of”a Rectangle. But if a Window
object can also be circular or triangular in shape, then it is not accurate to
say that a Window is a kind-of a Rectangle.
In reality, all you need to do is access the method area() in Rectangle,
for which you do not need an inheritance relationship. The simple alter-
native is for Window to create an object of the Rectangle class and to use
this object to access the method area(). Thus, we can say that Window
“uses”Rectangle which, in this case, is a more accurate model of the class
relationship and a simple approach to reusability.
Thinking object composition
With this new model in mind you can rethink the PetStore program devel-
oped in Chapter 16. Let's restate the case:
You are commissioned to develop a program for operating a pet shop
which sells dogs, cats, and birds to the public. The owner needs to iden-
tify each animal that is available and keep track of its location and sale
price. Specifically, the owner also wants to keep track of each dog and cat
breed and of the color of each bird. There is a plan to add other pet spe-
cies at a future date, so the system should be easily expandable. After an-
alyzing the software requirement you propose the following data
elements:
1. Each pet is given a name, which is remembered in a string variable.
2. Each pet has a sale price, stored in a variable of type double.
3. A variable of type int keeps track of the location of each pet in the store.
4. There is also species-specific data that must be remembered: the breed of
each dog, the breed of each cat, and the color of each bird.
Search WWH ::




Custom Search