In Java 101: Inheritance in Java, Part 1, you learned how to leverage inheritance for code reuse, by establishing is-a relationships between classes. Composition is a closely related programming technique that is used to establish has-a relationships instead. Whereas inheritance extends the features of one class to another, composition allows us to compose one class from another class. The distinction is subtle at first, but it will make more sense once you see it in code.
Composition vs inheritance
Has-a versus is-a relationships
In composition, a class has a field whose type is that of another class. For example, Vehicle
has a String
field named make
. It could also have an Engine
field named engine
and a Transmission
field named transmission
: