Possible Duplicate:
Prefer composition over inheritance?
What is the difference between inheritance and delegation in java?
How to use the following example in my project? Please can you guide me with delegation. I know about inheritance but do not have much knowledge about delegation. So, please give a proper reason. Why should I use this?
package com.m;
class RealPrinter { // the "delegate"
void print() {
System.out.println("something");
}
}
class Printer { // the "delegator"
RealPrinter p = new RealPrinter(); // create the delegate
void print() {
p.print(); // delegation
}
}
public class Tester {
// to the outside world it looks like Printer actually prints.
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}
When you delegate, you are simply calling up some class which knows what must be done. You do not really care how it does it, all you care about is that the class you are calling knows what needs doing.
If I were you though I would make an interface and name it
IPrinter(or something along those lines) which has one method namedprint. I would then makeRealPrinterimplement this interface. Finally, I would change this line:RealPrinter p = new RealPrinter();to this:IPrinter p = new RealPrinter().Since
RealPrinterimplementsIPrinter, then I know for sure that it has aprintmethod. I can then use this method to change the printing behaviour of my application by delegating it to the appropriate class.This usually allows for more flexibility since you do not embed the behaviour in your specific class, but rather leave it to another class.
In this case, to change the behaviour of your application with regards to printing, you just need to create another class which implements
IPrinterand then change this line:IPrinter p = new RealPrinter();toIPrinter p = new MyOtherPrinter();.