0

In the text, Effective Java by Joshua Bloch, he states 'Instead of extending an existing class, give your new class a private field that references an instance of the existing class. This design is called composition because the existing class becomes a component of the new one.' He further adds that one should always prefer composition over inheritance. Is this generally applicable to all general programming scenarios? Till now I have always used inheritance and considered it to be a solid concept. In what context should one decide to use composition?

Tom Thomas
  • 619
  • 2
  • 8
  • 24
  • One use case may be when you need to use classes from a third party API in your project and need some specific functionality, but these classes are marked as `final` so you cannot extend them. – Luiggi Mendoza Dec 02 '13 at 19:30
  • @LuiggiMendoza That's not preferring to use composition, that's being forced to use composition. – dcastro Dec 02 '13 at 21:46

0 Answers0