Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantage of object composition over class inheritance

Most design patten books say we should "Favor object composition over class inheritance."

But can anyone give me an example that inheritance is better than object composition.

like image 405
Howard Avatar asked Oct 20 '10 15:10

Howard


2 Answers

Inheritance is appropriate for is-a relationships. It is a poor fit for has-a relationships.

Since most relationships between classes/components fall into the has-a bucket (for example, a Car class is likely not a HashMap, but it may have a HashMap), it then follows the composition is often a better idea for modeling relationships between classes rather than inheritance.

This is not to say however that inheritance is not useful or not the correct solution for some scenarios.

like image 96
matt b Avatar answered Sep 20 '22 18:09

matt b


My simple answer is that you should use inheritance for behavioral purposes. Subclasses should override methods to change the behaviour of the method and the object itself.

This article (interview with Erich Gamma, one of the GoF) elaborates clearly why Favor object composition over class inheritance.

like image 32
Buhake Sindi Avatar answered Sep 21 '22 18:09

Buhake Sindi