But what does that mean?
Inheritance establishes an "Is-a" relationship between a base class and a subclass.
It's a quick and intuitive way to share attributes and behavior between classes.
The problem is that it is difficult to maintain because:
  1. Subclasses depend on parent class implementation. It is hard to navigate.
  2. Subclasses inherit all parent class behaviors, even if they don't need them.
  3. Overriding parent class behavior can introduce bugs.
Composition, on the other hand, forms a "Has-a" relationship.
The idea is to build more complex objects by combining simpler objects. Because:
  1. Components are reusable across different classes.
  2. It's easy to change behavior at runtime by changing the components of a class.
  3. Smaller, self-contained components are easier to change.
  4. Components are independent and interact through well-defined interfaces, reducing their dependencies.
Pros of Composition:
  • Easy to Test individual components.
  • Components are easier to change.
  • You can swap components at runtime.
  • Promotes Encapsulation and Single Responsibility Principle.
Cons of Composition:
  • Increase the number of objects in a system.
Favoring composition doesn't mean inheritance is an obsolete concept.
Inheritance is still useful, especially when objects need to behave in a similar way.