Inheritance or Encapsulation
The Problem
Encapsulation is a pain to implement, so we would like to avoid it as much as possible. Inheritance would be best, but it can not be chosen all the time. The question is when to use encapsulation. This question only appears whenever a language with a limited single inheritance model is used. The single inheritance model forces any class to subsume no more than one other class.
- Java uses the single inheritance model for classes, but uses the multiple inheritance model for interfaces.
- C++ has a dreadful multiple inheritance scheme that was obviously designed to make implementation easier, and ignores all intuition.
The Solution
Do not use inheritance when developing children in perpendicular directions. For example, consider a SQL abstraction class, like ODBC but sophisticated. We could inherit from this class and add database specific optimizations, one for each commercial database. We could also inherit from the abstraction class and add convenient routines. Unfortunately the latter could not benefit from the former directly; at least one of these classes must use encapsulation.
- Multiple inheritance allows the programmer to avoid facing the question between inheritance or encapsulation.