So I have been learning composition and inheritance. Now I understand inheritance is an "is-a" type relationship, and composition is a "has-a" relationship. But does this mean a composition simply refers to a class having an object (or field) of something?
-
6Yes. That's all it means. – Dawood ibn Kareem Oct 07 '13 at 21:30
-
2Note that this is trivially searchable. – Dave Newton Oct 07 '13 at 21:31
-
Hi, Chris. David Wallance and hexafraction are both correct. These links provide interesting discussion [Difference between Inheritance and Composition](http://stackoverflow.com/questions/2399544/difference-between-inheritance-and-composition). – paulsm4 Oct 07 '13 at 21:34
-
Note, too, the quote "Favor composition over inheritance. Design and document for inheritance or else prohibit it." – paulsm4 Oct 07 '13 at 21:37
2 Answers
When you have a situation where a class could extend another class (inheritance), or use another class as a field (composition), go for composition, because it allows you to change the implementation later without affecting any code that uses your class.
When you don't, you forever lock the implementation to be a subclass of the extended class. Any time you do that, it's bad.
An example from the JDK of where inheritance was chosen over composition is the Properties
class, which extends Hashtable
, when all needed was to use a Hashtable
internally and implement a suitable interface. That means you can't substitute in your own implementation of a Properties class, for example with a simple anonymous class.
There are far more examples from the JDK where they got it right, for example HashMap
uses a Hashtable
, but could easily be changed to use some other hash-based class without affecting its contract or API.
You should always strive to make classes flexible in their implementation.
See Liskov substitution principle

- 412,405
- 93
- 575
- 722
Basically yes, but it has more implications.
The outer object has to protect the enclosed objects from modifications to avoid data corruption. This is usually done through defensive copies creation. If the enclosed objects are immutable this is not necessary
Other implication is to have the enclosing object isolated from the object API so it may change in the future. Let's say the object uses an array and then it decide to use a list instead, by disallowing references to the internal object, the external may change implementation without breaking existing clients.
You may take a look to the chapter: "Prefer composition over inheritance" in the "Effective Java Book" which describes in great these and much other implications.

- 196,001
- 113
- 385
- 569