Designing with inheritance
Once you learn about polymorphism, it can seem that everything ought to be inherited, because polymorphism is such a clever tool. This can burden your designs; in fact, if you choose inheritance first when you’re using an existing class to make a new class, things can become needlessly complicated.
A better approach is to choose composition first, especially when it’s not obvious which one you should use. Composition does not force a design into an inheritance hierarchy. But composition is also more flexible since it’s possible to dynamically choose a type (and thus behavior) when using composition, whereas inheritance requires an exact type to be known at compile time. The following example illustrates this:
//: c07:Transmogrify.java
// Dynamically changing the behavior of an object
// via composition (the "State" design pattern).
import com.bruceeckel.simpletest.*;
abstract class Actor {
public abstract void act();
}
class HappyActor extends Actor {
public void act() {
System.out.println("HappyActor");
}
}
class SadActor extends Actor {
public void act() {
System.out.println("SadActor");
}
}
class Stage {
private Actor actor = new HappyActor();
public void change() { actor = new SadActor(); }
public void performPlay() { actor.act(); }
}
public class Transmogrify {
private static Test monitor = new Test();
public static void main(String[] args) {
Stage stage = new Stage();
stage.performPlay();
stage.change();
stage.performPlay();
monitor.expect(new String[] {
"HappyActor",
"SadActor"
});
}
} ///:~
A Stage object contains a reference to an Actor, which is initialized to a HappyActor object. This means performPlay( ) produces a particular behavior. But since a reference can be rebound to a different object at run time, a reference for a SadActor object can be substituted in actor, and then the behavior produced by performPlay( ) changes. Thus you gain dynamic flexibility at run time. (This is also called the State Pattern. See Thinking in Patterns (with Java) at www.BruceEckel.com.) In contrast, you can’t decide to inherit differently at run time; that must be completely determined at compile time.
A general guideline is “Use inheritance to express differences in behavior, and fields to express variations in state.” In the preceding example, both are used; two different classes are inherited to express the difference in the act( ) method, and Stage uses composition to allow its state to be changed. In this case, that change in state happens to produce a change in behavior.