When to use delegation instead of inheritance? [closed]

Could someone please explain when would I want to use delegation instead of inheritance?


Solution 1:

When you want to "copy"/Expose the base class' API, you use inheritance. When you only want to "copy" functionality, use delegation.

One example of this: You want to create a Stack out of a List. Stack only has pop, push and peek. You shouldn't use inheritance given that you don't want push_back, push_front, removeAt, et al.-kind of functionality in a Stack.

Solution 2:

They have nothing to do with each other. Delegation is a behavior. Inheritance is a model technique.

Inheritance is for modeling "is-a". A computer "is-a" electronic system.

Delegation is how methods provide results. Sometimes one object will delegate work to another object. Delegation can be via any relationship -- you can delegate to a superclass, to a member of a composite or aggregate, or any relationship.

Solution 3:

You may use delegation to multiple internal class instances to simplify their functionality into a common grouping. If your language doesn't implement multiple inheritance for instance you may inherit from one of the bases and wrap the other, delegating the functionality you want to expose to the underlying implementation. Inheritance also ties your class into the hierarchy of classes you are inheriting from where as with delegation you may keep your place in your own hierarchy and delegate calls to another.