Difference between Inheritance and Composition

前端 未结 17 2406
忘了有多久
忘了有多久 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:15

    The answer given by @Michael Rodrigues is not correct (I apologize; I'm not able to comment directly), and could lead to some confusion.

    Interface implementation is a form of inheritance... when you implement an interface, you're not only inheriting all the constants, you are committing your object to be of the type specified by the interface; it's still an "is-a" relationship. If a car implements Fillable, the car "is-a" Fillable, and can be used in your code wherever you would use a Fillable.

    Composition is fundamentally different from inheritance. When you use composition, you are (as the other answers note) making a "has-a" relationship between two objects, as opposed to the "is-a" relationship that you make when you use inheritance.

    So, from the car examples in the other questions, if I wanted to say that a car "has-a" gas tank, I would use composition, as follows:

    public class Car {
    
    private GasTank myCarsGasTank;
    
    }
    

    Hopefully that clears up any misunderstanding.

提交回复
热议问题