‘a subclass inherits inappropriate operations from a superclass’
The prime motivation for inheritance and composition in object oriented is code reuse . With inheritance, modifications on the superclass would lead to modifications of the subclass because of the implicit self-recursive re-entrant invocations . Such invocations can hinder the evolution of the model. Object composition depends on message forwarding. This means whenever an object cannot perform a task locally, it seeks assistance from other objects, ideally from ones that are part of it (inner objects), by sending them a message . In object composition, functionality is acquired dynamically at run time. As a result, composition promotes loosely coupled dependencies and flexible code reuse.
- Inheritance used where message forwarding would be more appropriate
- Forward messages from an object of the former subclass of an object of the former superclass
- Design loses the ability of subclass automatically to inherit new operations added later to superclass
- Reduced efficiency
Imagine where you have a simple inheritance (Figure 1), the operation getCountry() returns a string (country name). After new requirements you had to change the superclass to return a new class of type Country, then the FootballTeam subclass will be inheriting invalid operation (“inheritance breaks encapsulation.” ). Alternatively, by using composition, as in the Figure 2, the outer class FootballTeam would forward a message to the inner class SportsTeam to execute getCountry() operation, then the FootballTeam would still be able to return a string for its getCountry() operation via getName() public method from Country class.
- Clemens Szyperski. Component Software: Beyond Object-oriented Programming. 2nd edition, 2002
- Alan Synder. Encapsulation and inheritance in object-oriented languages. In Object-Oriented Programming Systems, Languages, and Applications Conference Proceedings, pages 38-45, 1986.
- Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley, 1995