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?
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.
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