Java Reference
In-Depth Information
Inheritance is sometimes abused, however. For example, consider a
Tire
class that
describes a car tire. Should the class
Tire
be a subclass of a class
Circle
? It
sounds convenient. There are quite a few useful methods in the
Circle
classČfor
example, the
Tire
class may inherit methods that compute the radius, perimeter, and
center point, which should come in handy when drawing tire shapes. Though it may
be convenient for the programmer, this arrangement makes no sense conceptually. It
isn't true that every tire is a circle. Tires are car parts, whereas circles are geometric
objects. There is a relationship between tires and circles, though. A tire has a circle as
its boundary. Java lets us model that relationship, too. Use an instance field:
public class Tire
{
. . .
private String rating;
private Circle boundary;
}
The technical term for this relationship is aggregation. Each
Tire
aggregates a
Circle
object. In general, a class aggregates another class if its objects have objects
of the other class.
Aggregation (the has-a relationship) denotes that objects of one class contain
references to objects of another class.
Here is another example. Every car is a vehicle. Every car has a tire (in fact, it has
four or, if you count the spare, five). Thus, you would use inheritance from
Vehicle
and use aggregation of
Tire
objects:
public class Car extends Vehicle
{
. . .
private Tire[] tires;
}
539