0

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?

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
Chris London
  • 81
  • 1
  • 9

2 Answers2

1

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

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

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.

OscarRyz
  • 196,001
  • 113
  • 385
  • 569