Originally posted by mini mehta:
Can anybody explain following statement :
"Favour object composition over inheritance"
On top of what has been mentioned, inheritance is a static notion, while composition is a dynamic one; more specifically, having an instance of a subclass, this instance cannot be easily transfered to an instance of another subclass at run-time (ie. change of types at run time is hard to do with this setting). With composition, you can associate another component instance (which implements same interface) at run time.
Change of types at run time can be design and implemented using the State pattern though; how? using composition where the component keeps track of the type at run time.
But inheritance definitely has its place in design of classes, where the IS-A of model subclass is stable and to exploit
polymorphism. A careless use of inheritance can give rise to class explosion in class hierarchies; for example when using inheritance to model options of features in an object.
------------------
Jaime Nino
Author of:
An Introduction to Software Construction with Java