What is delegation in Java? Can anyone give me a proper 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.
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.
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)
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() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With