File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes difference between inheritance and composition Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "difference between inheritance and composition" Watch "difference between inheritance and composition" New topic

difference between inheritance and composition

Srinivas Rallapalli

Joined: May 20, 2003
Posts: 18
is there any difference between inheritance and composition. which is better to use.
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
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.

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Rodrigo Dinis
Ranch Hand

Joined: May 28, 2003
Posts: 40
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.

Rodrigo Dinis
Brasilia - BRASIL
Philip Shanks
Ranch Hand

Joined: Oct 15, 2002
Posts: 189
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.

Philip Shanks, SCJP - Castro Valley, CA
My boss never outsources or has lay-offs, and He's always hiring. I work for Jesus! Prepare your resume!
I agree. Here's the link:
subject: difference between inheritance and composition
It's not a secret anymore!