Choosing composition vs. inheritance

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Bruce Eckel’s Thinking in Java Contents | Prev | Next

vs.
inheritance

Sometimes
it makes sense to allow the class user to directly access the composition of
your new class; that is, to make the member objects
public.
The member objects use implementation hiding themselves, so this is a safe
thing to do and when the user knows you’re assembling a bunch of parts,
it makes the interface easier to understand. A
car
object is a good example:

//: Car.java
// Composition with public objects
 
class Engine {
  public void start() {}
  public void rev() {}
  public void stop() {}
}
 
class Wheel {
  public void inflate(int psi) {}
}
 
class Window {
  public void rollup() {}
  public void rolldown() {}
}
 
class Door {
  public Window window = new Window();
  public void open() {}
  public void close() {}
}
 
public class Car {
  public Engine engine = new Engine();
  public Wheel[] wheel = new Wheel[4];
  public Door left = new Door(),
       right = new Door(); // 2-door
  Car() {
    for(int i = 0; i < 4; i++)
      wheel[i] = new Wheel();
  }
  public static void main(String[] args) {
    Car car = new Car();
    car.left.window.rollup();
    car.wheel[0].inflate(72);
  }
} ///:~ 

Because
the composition of a car is part of the analysis of the problem (and not simply
part of the underlying design), making the members public assists the client
programmer’s understanding of how to use the class and requires less code
complexity for the creator of the class.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read