File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes OO, Patterns, UML and Refactoring and the fly likes COMPOSITE PATTERN Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring


Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1868
Composite pattern hides its implementation using private inheritance.

i do not understand the statement above. Is it a correct statement. If so what does it mean??


IBM Application Server Forum Moderator
Eddy Chang

Joined: Apr 05, 2001
Posts: 27

I'll try to demonstrate how using composition is essentially using private inheritance by using a few examples.
Consider the Address and Customer classes below.


Say that we now want to add an address to a customer, and we want to reuse the Address class functionality.
In object oriented programming, there are 3 ways that you can do this.
1. Use composition (supported in java and C++)
2. Use public inheritance (supported in java and C++)
3. Use private inheritance (supported in C++ but not java)
1. Using composition
Using composition, you can re-use the implementation of the Address class. You must supply the interface to access the address object.
The Customer class looks like:

2. Using public inheritance
In public inheritance, the interface and the implementation of the Address class is inherited.
The Customer class looks like:

3. Using private inheritance
In private inheritance, you inherit the implementation of the Address class only, you do not inherit the interface of the Address class, which is similar to composition reusing the implementatin of the Address class.
The Customer class would look something like the following if java supported private inheritance.

I hope that you can see from the examples above that using composition is effectively the same as using private inheritance.
Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1868
Thanks that was really good. But then it looks like a composite in this case is similar to a Object based Adapter which is similar.
Dave Liu

Joined: Mar 06, 2001
Posts: 2
The question was for the Composite Pattern, but the example was talking about composition. Those are two different things right?
Joe Nguyen
Ranch Hand

Joined: Apr 20, 2001
Posts: 161
This isn't a composite pattern. It is rather an association between the customer and address classes. Composite pattern uses private inheritance because it only exposes the Common public methods of all the children classes to the user. As a result, it hides all theuncommon methods from the user.
Public inheritance means all child's public methods would be expose to the user. If one uses composite pattern and later wants to expose one's of a particular child class, it would be a mess.
Please, share your thoughts...
I agree. Here's the link:
It's not a secret anymore!