Composition vs Delegation
Hi,
Composition is about the relationships between objects.
Delegation is about passing work from one object to another.
So both are different.
Example for Delegation:-
class RealPrinter { // the "delegate"
void print() {
System.out.print("something");
}
}
class Printer { // the "delegator"
RealPrinter p = new RealPrinter(); // create the delegate
void print() {
p.print(); // delegation
}
}
public class Main {
// to the outside world it looks like Printer actually prints.
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}
The same example also denotes composition as well as where are not using inheritance for RealPrinter class as we are creating an instance of it in the Printer class
and making use of its method. Please correct me if i have gone wrong . If not please let me know how we can use composition in the above example.
Thanks.