Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use delegation instead of inheritance? [closed]

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

like image 436
Cuga Avatar asked May 07 '09 01:05

Cuga


People also ask

What's the difference between inheritance and delegation?

Delegation is an alternative to inheritance for reusing code among multiple classes. Inheritance uses the IS-A relationship for re-use; delegation uses the HAS-A reference relationship to do the same. Inheritance and delegation have the same kind of relationship that, say, Aspirin and Tylenol, have.

What are some alternatives to inheritance?

Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance.

Can delegate be inherited?

No. According to the C# documentation, delegate types are sealed, and you cannot create a new delegate type that inherits from an existing one.

Does delegation promote code reuse?

Delegation is a technique that promotes code reuse by allowing runtime function invocation in the context of a specific instance – regardless of the hierarchical lineage of instance and function.


2 Answers

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.

like image 71
Anzurio Avatar answered Sep 21 '22 20:09

Anzurio


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.

like image 22
S.Lott Avatar answered Sep 20 '22 20:09

S.Lott