views:

318

answers:

3

I thought to seek this answer from stackoverflow community that how to decide to go for composition or generalization when we are designing classes.

+1  A: 

Ask yourself if the relationship between the two classes are of a "is-a" or a "has-a" type

Maurice Perry
+1  A: 

You use composition when you have a class that has a set of another objects, in any quantity. Use generalization when you have a class that shares common properties with a set of objects, but can also have other diferent properties or behavior.

For example, a Car has components like the engine, wheels, etc. This a composition relationship. But a Vehicle is a generalization of a Car, because you can have another types of Vehicles with diferent properties, like a Truck. Car and Truck are derived classes of Vehicle.

El Cheicon
+1  A: 

If we're talking about public inheritance (IS_A), the key is to understand the Liskov Substitution Principle and what it means with respect to inheritance. In particular, it means that the IS-A relationship is context dependent which is an often overlooked aspect of public inheritance.

To use the example above, the Car and Truck classes should only be derived from Vehicle if they can be substituted for the Vehicle class in any program written to use the Vehicle class without impacting the calling code.

If we're talking about implementation inheritance (aka, private inheritance in C++), you should prefer composition over inheritance as a re-use mechanism.

Rob Scott