implementation inheritance vs composition vs delegation

Hi,

To reuse code in java we use

implementation inheritance, composition , delegation.


I wonder why interface implentation cannot be used for 'code reuse'.

What are advantages, disadvantages, practical uses of each of
implementation inheritance vs composition vs delegation.

Please advise. Any ideas, resources, sample code highly appreciated. thanks in advance
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dpearsonCommented:
I think it's fair to say that today many people view implementation inheritance as a poor design choice.  It brings in a lot of problems compared to composition, so it should be used in only limited situations.

There are a number of problems with inheritance compared to using composition (or delegation):
1) The entire interface is exposed, even if only a subset is required.

E.g.
   class MyList extends List<Integer> { }

compared to

    class MyList {
         private List<Integer> m_List = new ArrayList<Integer>() ;
         public void add(int x) { m_List.add(x) ; }
         public int size() { return m_List.size() ; }
     }

The first one using inheritance exposes a huge interface - such as "retainAll" and other rarely used methods.  That's fine if the intention is to support everything, but if only a simple subset is needed, then the second approach makes it much easier to change the internal representation to something else.

2) If the parent class is changed after the subclass has been created, the behavior of the subclass can change in unexpected and complex ways.

E.g. Let's assume we have overridden 'add' to always print(x) when a value is added to the list.

class MyList extends List<Integer> {
     public void add(Integer x) { super.add(x) ; print(x) ; }
}

Now consider the
"addAll(Collection c)" method in List.

This could be implemented by
a) Calling "add(x)" over and over
or
b) Calling to add items to the internal data structure without calling the "add" method.

Changing from (a) to (b) [or the other way] would change whether or not the "print" method was called in the subclass.  In (a) it would be.  In (b) it would not be.

But BOTH are valid implementations of the superclass.

So this is a case where the implementer of the superclass makes a change and breaks the subclass.  This can't happen with composition or delegation.

So the general answer is "prefer composition where possible".  Only use inheritance when it is clearly required.

Doug
0
girionisCommented:
It is safe to use inheritance when the superclass and subclass implementation is under the control of the same programmer. It is also safe to use it when extending classes specifically designed for inheritance. But inheriting from arbitrary classes from thrid party APIs is risky and can lead to fragile software because a subclass depends onthe parent class for its proper function. If the superclass implementation changes from release to release then the functionality of the subclass may break, even if the code hasn't changed.

So you use composition to avoid any problem since the existing class becomes a component of the new class. Each method of the new class invokes the corresponding method of the contained class.

If you want to know more about this I'd suggest you read the "Effective Java" by Joshua Bloch (a book that should be in the bookcase of every Java developer who respects him/herself). He dedicates a few chapters (items) on the inheritance vs composition paterns.
0
gudii9Author Commented:
E.g.
   class MyList extends List<Integer> { }

you mean implements as below right

E.g.
   class MyList implements  List<Integer> { }
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

dpearsonCommented:
Oops - yes.  Should be implements not extends since List is an interface not an abstract class.

Doug
0
gudii9Author Commented:
>>>There are a number of problems with inheritance compared to using composition (or delegation):


Is composition is same as delegation in this case? Please advise.
0
dpearsonCommented:
Yes - composition and delegation are basically the same concept here.

You are delegating the work of implementing the class to components (rather than to a base class).

Doug
0
gudii9Author Commented:
It is also safe to use it when extending classes specifically designed for inheritance.

How do we know if it safe to use it specifically designed for inheritance.

Please advise


The first one using inheritance exposes a huge interface - such as "retainAll" and other rarely used methods.

Changing from (a) to (b) [or the other way] would change whether or not the "print" method was called in the subclass.  In (a) it would be.  In (b) it would not be.

what is 'retailAll' you referred. I am still not very clear on it. Can you please elaborate with probably some simple example
0
dpearsonCommented:
The point here isn't specific to retainAll - just to the number of methods in the interface.

If you look at:
http://docs.oracle.com/javase/7/docs/api/java/util/List.html
and it's parent:
http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html

you get 40 methods when you create a new class inherited from List.

The point here is that code using your class probably doesn't need to use all 40 of those methods.  A class which exposes a smaller number of methods is almost always better than one exposing a lot of methods.  So you should only expose all 40 of the methods from List if you really plan to use them...which you probably don't.

It's another example of why delegation/composition is usually better than inheritance.

Doug
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.