Use a decorator Design Pattern.
and here's a simplified example of the decorator pattern.
(adapted from the interwebs and polygenelubricants' answer on SO)
Note: before we begin remove the abstract keyword from the interface, that's wrong syntax
The class hierarchy is restructured as static
inner classes so that the whole example is contained in one compilation unit (as seen on ideone.com):
Here's a diagrammatic overview of intended class hierarchy

public class AnimalDecorator {
static interface Animal {
public String makeNoise();
public void wagTail();
//other methods
}
static class Dog implements Animal {
public final String makeNoise() { return "woof"; }
public final void wagTail() { //do wag tail action }
}
static class DogDecorator implements Animal {
//delegate
private Animal animal;
public DogDecorator (Animal animal){this.animal = animal;}
public String makeNoise() { animal.makeNoise();}
public void wagTail() { animal.wagTail();}
}
static class LoudDog extends DogDecorator {
@Override public String makeNoise() {
return "WOOF WOOF WOOF!!!";
}
}
}
So here we have a simple Animal
hierarchy, with Dog
subclass. We also have a DogDecorator
decorator -- also an Animal
-- that simply delegates all methods to another Animal
. That is, it doesn't really do any effective decoration, but it's ready to be subclassed so that actual decorations can be added.
We only have two methods here, makeNoise()
and wagTail()
. We then create the class we want LoudDog
and use it. (Consider the case where Animal
has many methods; then Normal
would be most valuable).
Note that we can even stack one decoration on top of another. The exact implementation details may vary, but this simplified example pretty much captures the essence of the decorator pattern.
Steps
- Subclass the original "Component" class into a "Decorator" class (see UML diagram);
- In the Decorator class, add a Component pointer as a field;
- Pass a Component to the Decorator constructor to initialize the Component pointer;
- In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
- In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.
See also
- Effective Java 2nd Edition, Item 18: Prefer interfaces to abstract classes
Related questions