What is delegation? When would I want to use it?
Asked Answered
X

2

7

In OOP, a term delegation is mentioned. How is this modelled in a class? I searched on yahoo etc but got links to delegates.

Xerox answered 15/1, 2011 at 18:36 Comment(0)
F
26

Imagine you have the classes Car and Engine:

public class Car {
   private Engine engine = new Engine(); //or inject it externally

   public void start() {
       engine.start();
   }
}

In this example the Car delegates to the underlying Engine. The user of the car cannot directly start the engine (unless he is a mechanic). But he can tell the car to start, and the car in turn tells the engine to start.

You'd want to use it whenever you use object composition and you need to use a method of one of the composing objects. In that case you create a method that delegates to it.

Fifi answered 15/1, 2011 at 18:38 Comment(2)
+1 To extend on this. Inheritance also does delegation, implicitly to the parent(s). What you describe above is explicit delegation.Hayton
@Hayton I think inheritance doesn't do delegation. Delegation is handling the responsibility to some other object. The other object can be of the same class or a totally different class. While in case of inheritance, every object shares the same set of methods.Constipation
E
0

Delegation is like inheritance except instead of class2 having copied functions and variables from class1 class2 just gets class1 to do that stuff for it and class2 focuses on doing and having the extra functions and variables you give it. One obvious advantage of this is it saves space on your computer.

Edroi answered 9/10, 2018 at 21:57 Comment(1)
This does not seem to add anything the accepted answer doesn't.Cutout

© 2022 - 2024 — McMap. All rights reserved.