Composition and Interfaces in OOP World

In the object-oriented programming world, the concept of inheritance has been criticized for a long time.

There are quite a lot of arguments:

  • A derived class inherits all the parent’s data and behavior that is not always necessary. When modifying a parent class, some data and behavior that are not supposed to be in the derived class get into it;
  • Virtual methods are less productive. If a language allows declaring a non-virtual method, what would you do when you need to override one in an inherited method? You can mark the method with the new keyword, however, in this case, polymorphism will not work. The consequent use of this object may cause unexpected behavior, depending on the type the object is going to be converted to.
  • The vast majority of languages do not allow multiple inheritance.
  • There are tasks where inheritance is helpless. Consider the case, when you need to create a container (array, list, or set) and implement the same behavior for elements with different types. In addition, you need to provide static typing. In this case, generics will come to help.

(more…)