aspose file tools*
The moose likes Java in General and the fly likes composition over inheritance? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "composition over inheritance?" Watch "composition over inheritance?" New topic
Author

composition over inheritance?

chad stevens
Ranch Hand

Joined: Aug 20, 2002
Posts: 88
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

Joined: Jul 13, 2001
Posts: 269
See the UML Forum. You will find some discussions on it.
W.
Joanne Fiorilli
Greenhorn

Joined: Jan 23, 2003
Posts: 5
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

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: composition over inheritance?