• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference between inheritance and composition

 
Srinivas Rallapalli
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is there any difference between inheritance and composition. which is better to use.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a word yes. But sometimes the distinction may not be so clear because the super of a subclass may itself be a composite and in the case of many design patterns often is. So which is better? That depends. The general rule would be not to have very long inheritance trees. You must remember that inheritance is a static quality, that is you are locked in at compile time. On the other hand composition tends to be more dynamic: you can defer creation of composites based on runtime considerations. They both have their place in design, the trick is figuring which goes where.
 
Rodrigo Dinis
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear,
Normally you must use composition when the class witch that you�re creating have another class inside it, like a door that have a key. And you will use heritance when need to express a hierarchy like you have a door made of wood and another made of plastic (let us say) it stay:
Door (Superclass)
/ \
DoorWood DoorPlastic
I hope you understood.
 
Philip Shanks
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see the difference as simply this, inheritance means "is a", while composition means "has a". If you are spending appropriate time in the design phase, then usually it will be clear when to use which. Another way to view it is the difference between extending and wrapping.
Personally, I tend to follow the excellent advice of Joshua Bloch (as found in his "Effective Java: Programming Language Guide") when he says "Favor composition over inheritance." I won't repeat his argument here, but it partly has to do with the reality that inheritance sets up very strong and often undesirable code dependencies.
An excellent example of when NOT to use inheritance can be found in the Java API itself: look into the java.util.Properties class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic