Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Composition vs Delegation

User_19BPUMar 26 2012 — edited Mar 26 2012
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 23 2012
Added on Mar 26 2012
2 comments
1,147 views