Containment
(Aggregation)
A class can contain
another class (a has-a relationship):
// Wheel.java
public class Wheel
{
/* Details... */
}
|
// Car.java
public class Car
{
public final int WHEEL_COUNT = 4;
// Constructor
public Car(String make, int maxSpeed)
{
m_make = make; m_maxSpeed = maxSpeed;
m_wheels = new Wheel[WHEEL_COUNT];
for (int i = 0; i < WHEEL_COUNT; i++)
m_wheels[i] = new Wheel();
}
// Data
private String m_make;
private int m_maxSpeed;
private Wheel m_wheels[]; // a Car has wheels
}
|
Inheritance
...or a class can inherit
from another class (an is-a or is-a-kind-of
relationship):
// WheeledVehicle.java
public class WheeledVehicle
{
// Constructor
public WheeledVehicle(int wheelCount)
{
m_wheelCount = wheelCount;
m_wheels = new Wheel[wheelCount];
for (int i = 0; i < wheelCount; i++)
m_wheels[i] = new Wheel();
}
// Data
private int m_wheelCount;
private Wheel m_wheels[];
// a WheeledVehicle has wheels
}
|
// Truck.java
public class Truck extends WheeledVehicle
// Truck is-a-kind-of WheeledVehicle
{
// Constructor
public Truck(String make, int maxSpeed)
{
super(WHEEL_COUNT);
m_make = make; m_maxSpeed = maxSpeed;
}
// Data
private static int WHEEL_COUNT = 4;
private String m_make;
private int m_maxSpeed;
}
|
Whether to use inheritance
or containment depends on what youre
trying to do:
Assuming that you are trying to decide
whether a class B should inherit from a class A, or
contain a class A, you should ask yourself:
"Is B a kind of A?"
If so, then use inheritance.
"Does B have an A?"
If so, then use containment.
Sometimes the answer is
obvious:
"Is a Car a kind
of Vehicle?"
"Does a Car have
an Engine?"
and sometimes its not:
"Is a Point a kind
of Location?"
"Does a Point have a
Location?"
|