What is inheritance, and when does extending a class make sense rather than composing one?
Inheritance is a way of saying that one class is a special kind of another class. The child class gets the fields and the methods of the parent, and it can add more or change some of them.
public class Main {
public static void main(String[] args) {
Notification email = new EmailNotification("order shipped");
Notification sms = new SmsNotification("order shipped");
System.out.println(email.send());
System.out.println(sms.send());
}
}
And here is what that looks like in code.
public abstract class Notification {
protected final String message;
protected Notification(String message) {
this.message = message;
}
public abstract String send();
}
public class EmailNotification extends Notification {
public EmailNotification(String message) {
super(message);
}
@Override
public String send() {
return "email: " + message;
}
}
And so when does extending a class make sense rather than composing one? The rule is simple. Extend when the child really is a special kind of the parent, and compose when the child merely uses the parent.
the question to ask the answer
------------------------ -----------------------------------------
is the child a kind of yes, then extend
the parent?
would the phrase "a X no, then compose
is a Y" make sense?
So an EmailNotification is a Notification, and that sentence is true. But an Order is not a Notification, so an Order should hold a Notification rather than extend it.
// Compose: the order uses a notification, it is not one.
public class Order {
private final Notification notification;
public Order(Notification notification) {
this.notification = notification;
}
public void ship() {
System.out.println(notification.send());
}
}
And there are three practical reasons to prefer composition, and they are the reason most modern code uses it more often.
The first one is that inheritance couples the two classes together. If the parent changes then the child has to change as well, and if you do not own the parent then you cannot make that change safely.
The second one is that a class can only extend one class in Java, but it can hold as many collaborators as it needs. So composition does not run out.
The third one is that inheritance gives you the wrong kind of reuse. When a class inherits, it takes everything from the parent, even the parts it does not want. When a class composes, it takes exactly the part it needs.
So the rule to remember is this. Extend for a real is-a relationship, and compose for everything else.
The last question in this topic is about how to test a proposed parent and child pair.