Are Composition and Inheritance the same?
If I want to implement the composition pattern, how can I do that in Java?
Are Composition and Inheritance the same? If I want to implement the composition pattern,
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
They are absolutely different. Inheritance is an “is-a” relationship. Composition is a “has-a”.
You do composition by having an instance of another class
Cas a field of your class, instead of extendingC. A good example where composition would’ve been a lot better than inheritance isjava.util.Stack, which currently extendsjava.util.Vector. This is now considered a blunder. A stack “is-NOT-a” vector; you should not be allowed to insert and remove elements arbitrarily. It should’ve been composition instead.Unfortunately it’s too late to rectify this design mistake, since changing the inheritance hierarchy now would break compatibility with existing code. Had
Stackused composition instead of inheritance, it can always be modified to use another data structure without violating the API.I highly recommend Josh Bloch’s book Effective Java 2nd Edition
Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.
See also: