Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delegation example regarding java context

Tags:

What is delegation in Java? Can anyone give me a proper example?

like image 884
sarah Avatar asked Jun 07 '10 11:06

sarah


People also ask

What is delegate in Java with example?

Delegation is simply passing a duty off to someone/something else. Delegation can be an alternative to inheritance. Delegation means that you use an object of another class as an instance variable, and forward messages to the instance.

Does Java support delegate?

Java 8 has a feature quite like delegates. It's called lambdas. @tbodt to be more correct, Java 8 has a feature quite like delegates. It's called functional interfaces.


2 Answers

That's delegation - exactly like in the real world:

public interface Worker() {   public Result work(); }  public class Secretary() implements Worker {     public Result work() {      Result myResult = new Result();      return myResult;    }     }  public class Boss() implements Worker {     private Secretary secretary;     public Result work() {      if (secretary == null) {         // no secretary - nothing get's done         return null;      }      return secretary.work();    }     public void setSecretary(Secretary secretary) {        this.secretary = secretary;    } } 

(Added Worker interface to get closer to the Delegator pattern)

like image 109
Andreas Dolk Avatar answered Oct 13 '22 01:10

Andreas Dolk


If you're referring to the delegation pattern, wikipedia has a great example, written in java.

I believe the longer example of the page above is the best one:

interface I {     void f();     void g(); }  class A implements I {     public void f() { System.out.println("A: doing f()"); }     public void g() { System.out.println("A: doing g()"); } }  class B implements I {     public void f() { System.out.println("B: doing f()"); }     public void g() { System.out.println("B: doing g()"); } }  class C implements I {     // delegation     I i = new A();      public void f() { i.f(); }     public void g() { i.g(); }      // normal attributes     void toA() { i = new A(); }     void toB() { i = new B(); } }   public class Main {     public static void main(String[] args) {         C c = new C();         c.f();     // output: A: doing f()         c.g();     // output: A: doing g()         c.toB();         c.f();     // output: B: doing f()         c.g();     // output: B: doing g()     } } 
like image 26
aioobe Avatar answered Oct 12 '22 23:10

aioobe