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:
-
Subclasses depend on parent class implementation. It is hard to navigate.
-
Subclasses inherit all parent class behaviors, even if they don't need them.
-
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:
-
Components are reusable across different classes.
-
It's easy to change behavior at runtime by changing the components of a class.
-
Smaller, self-contained components are easier to change.
-
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.