Difference between Inheritance and Composition
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 C
as a field of your class, instead of extending C
. A good example where composition would've been a lot better than inheritance is java.util.Stack
, which currently extends java.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 Stack
used 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
- Item 16: Favor composition over inheritance
- Item 17: Design and document for inheritance or else prohibit it
Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.
See also:
- Composition versus Inheritance: A Comparative Look at Two Fundamental Ways to Relate Classes
What is the difference between inheritance and composition?
Inheritance expresses a is-a
relationship, while composition expresses a has-a
relationship between the two classes.
An example for composition is a polygon. It has a ordered sequence of Points. In C++ terms:
struct Polygon {
std::vector<Point> points;
};
While an logic_error
is a exception
:
struct logic_error : public exception {
};
Inheritance vs Composition: Does composition effectively solve dependency issues? [Effective Java]
Ok so I looked up what @LeiYang recommended and came to realize the my question wasn't valid. The given paragraph states "a subclass depends on the implementation details of its superclass for its proper function" - which Object Composition would have no problem with, as it merely makes use of provided methods as is(without overriding). Therefore Object Composition
doesn't violate encapsulation and is relatively stable compared to Inheritance
.
What does composition mean in the composition vs inheritance debate?
In short
This is a terminological ambiguity. Almost all articles on the bridge pattern are directly inspired from the Gang of Four (GoF) who first defined this design pattern. And this is the cause of the ambiguity:
They used the term composition to mean object composition and not UML composition.
At the time they wrote their book, UML was not yet defined. Their graphical notation uses the hollow diamond with a different meaning than UML.
They were first to mention composition over inheritance, with the meaning of object composition as opposed to class inheritance.
More details
GoF's object composition is not UML composition
Object composition is the OOP technique that aims at making more complex objects by assembling simpler objects. It's defined on page 19 of the book:
Here, new functionality is obtained by assembling or composing objects to get more complex functionality. Object composition requires that the objects being composed have well-defined interfaces. This style of reuse is called black-box reuse, because no internal details of the objects are visible.
In UML this technique corresponds to the implementation of an association, a shared aggregation or an UML composition. But unlike UML composition, it does not imply exclusive ownership nor lifecycle management.
GoF graphical notation is not UML
The graphical notation of class diagram used in the book looks very much like UML. This is because it is based on OMT, a predecessor of UML. But there are slight differences in the use of symbols, as you can read on page 364 of GoF:
An object reference representing a part-of or aggregation relationship is indicated by an arrowheadded line with a diamond at its base.
In UML, a composition (black diamond) would match this definition. But UML-composition adds more requirement, such as an exclusive ownership and responsibility for the component's lifecycle. This is more restrictive than object composition and reference-based aggragation.
In UML a shared aggregation (hollow diamond) or even a simple association (no diamond) would also perfectly match this definition, keeping in mind that UML does not define the semantics of shared aggregation.
Composition over inheritance
GoF are as far as I know, the first who recommended composition over inheritance. Page 20 of their pioneering work they made the following very precise statement (highlighting by me):
Favor object composition over class inheritance
We all like short mantras. Hence, this was quickly taken over without "object" and "class".
Conclusion
Whenever people speak about GoF patterns, you'll face the risk that aggregation or composition symbols might not be accurate, and that composition could have several meanings. So, you need to read it with critical thinking and an open mind. As patterns are not magical recipes, and may anyway need to be adapted to your own constraints, this state of mind can only be of advantage for you ;-)
Related Topics
How to Read a File from Jar in Java
How to Enter Quotes in a Java String
Difference Between Fetchtype Lazy and Eager in Java Persistence API
Java.Util.Date VS Java.Sql.Date
Java - Escape String to Prevent SQL Injection
Does a Lambda Expression Create an Object on the Heap Every Time It's Executed
Questions About Java'S String Pool
How to Increase the Java Stack Size
Quality of Image After Resize Very Low - Java
Why Does the Default Object.Tostring() Include the Hashcode
Program Not Accessing Method Paintcomponent() of Extended Jpanel Class
How to Convert Epoch to MySQL Timestamp in Java
What Are Enums and Why Are They Useful
Draw a Line in a Jpanel With Button Click in Java
Fastest Way to Determine If an Integer'S Square Root Is an Integer