Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

composition over inheritance?

 
chad stevens
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering while reading through a few articles some claim to use one over the other yet none give a good concise answer to this question. They also talk about Forwarding methods, why use these - composition/forwarding approach? If composition is so powerful, why is it then that inheritance seems to be used more?
 
Wilfried LAURENT
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the UML Forum. You will find some discussions on it.
W.
 
Joanne Fiorilli
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chad..
Use inheritance when you have a 'is-a' relationship, use composition when you have a 'has-a' relationship. For example, if a manager is an employee. This can be inheritance. However, a manager can play and employee role as well as another role. In terms of this you can use composition. Inheritance is a static notion, composition is a dynamic one. It is often said that inheritance can break encapulation, especially across packages. You must carefully apply it and make sure what you are subclassing really is what the superclass also is. Don't use inheritance just to get polymorphism and don't use it for the sole pupose of code reuse either. Use composition in this case. I hope this will help you.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Joanne Fiorilli:
Use inheritance when you have a 'is-a' relationship, use composition when you have a 'has-a' relationship.

This is an often cited heuristic, but I think it is dangerously flawed. Inheritance and composition are tools to manage source code dependencies - domain dependencies don't help much here. An often cited example is the ellipse and circle problem - a circle "is an" ellipse, but to use inheritance here *might* get you in some trouble.
Do a search on "composition versus inheritance" - there are many discussions on the subject here on Javaranch and elsewhere on the net.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic