Translate

Search This Blog

Sunday 26 June 2011

Inheritance versus composition in Java

are two important concepts you should swear by. Both help us to relate classes and achieve code resuse. But which one do we use?
Comparing inheritance and composition.
  1. In inheritance, a change to the method interface/definition of the superclass ripples down to the sublasses (if the method is overriden) and also to the clients of the sublasses thus making the superclass very fragile. In case of composition the change is limited to the containing class and not the clients.
  2. With inheritance, you cannot change the overriden method in the subclass without changing the superclass; reason it wont compile. With composition, you can change the interface of the method in the containing class that uses the method/behaviour of the contained class without touching it.
  3. In case of inheritance the classes are bound statically at compile time or as soon as the subclass is defined and will remain with the subclass till its lifetime. where as in case of composition, the behaviour can be changed at runtime.
  4. Though, with inheritance you can add new subclasses without affecting the code. Where as this is not the case with composition, unless you use composition with interface.
Going by the definition of inheritance, one should use it only if there is a IS-A relationship between classes and should not be merely used to get code re-use or polymorphism.
If you want to reuse code and there is no IS-A relationship , use composition and if you need polymorphism, but there is no IS-A relationship, use composition with interfaces.

I will add examples to explain each comparison points, in my next iteration of this post.
Resources

No comments:

Post a Comment

Please use proper blogging etiquette while posting comments.

Note: only a member of this blog may post a comment.