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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…