What is the difference between a has-a relationship and an is-a relationship, and how do you decide which one you have?
A has-a relationship means one object holds the other. An is-a relationship means one object is a special kind of the other. The test is the sentence "a X is a Y" and "a X has a Y".
public class Main {
public static void main(String[] args) {
Car car = new Car(new Engine("v8"));
car.start();
}
}
And here is the has-a version, with the car holding the engine.
public class Car {
private final Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
public void start() {
engine.start();
}
}
And here is the is-a version, with the car extending a vehicle.
public class Vehicle {
public void start() {
System.out.println("starting");
}
}
public class Car extends Vehicle {
private final Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
@Override
public void start() {
engine.start();
super.start();
}
}
So how do you decide which one you have? You write both sentences out loud with the real names in them.
the pair "a X is a Y" "a X has a Y" the answer
----------------------------- -------------- -------------- ------------
Car and Engine no yes has-a
Car and Vehicle yes yes is-a
Order and LineItem no yes has-a
SavingsAccount and Account yes yes is-a
And there are two things that make the is-a relationship stronger than it looks. The first one is that the child must be usable wherever the parent is used, so it has to keep all the promises of the parent. The second one is that it can only have one parent, so the is-a relationship uses up the one chance the class has.
And the has-a relationship has no such limit. An object can hold as many other objects as it needs, and each one can be replaced at run time.
// The engine is chosen by the caller, so it can be swapped.
Car petrol = new Car(new PetrolEngine());
Car electric = new Car(new ElectricEngine());
So the rule to remember is this. If a X is a Y then extend, and if a X has a Y then hold it in a field.
The last question in this topic is about why most designs prefer has-a.