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. Eddy
Joined: Jul 28, 2000
Hi, 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.
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...