Difference between Inheritance and Composition

前端 未结 17 1845
忘了有多久
忘了有多久 2020-11-22 02:35

Are Composition and Inheritance the same? If I want to implement the composition pattern, how can I do that in Java?

17条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 03:27

    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

提交回复
热议问题