JavaAdvanced#design-patterns#oop

What is the difference between composition and inheritance, and why is 'favor composition over inheritance' recommended?

Inheritance creates tight is-a coupling to a parent class and can break encapsulation across hierarchy changes. Composition builds has-a relationships by combining objects, offering more flexibility, easier testing, and avoiding fragile base class problems.

Example
// Inheritance (tight coupling)
class Car extends Engine {}
// Composition (flexible)
class Car { private Engine engine; Car(Engine engine) { this.engine = engine; } }

Related Questions

1
JavaAdvanced#design-patterns

What is the Template Method pattern?

Open
2
JavaBeginner#jdbc

What is JDBC and what are its main components?

Open
3
JavaBeginner#jdbc

What is the difference between Statement and PreparedStatement?

Open