Difference between Inheritance and Composition

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

    Composition means HAS A
    Inheritance means IS A

    Example: Car has a Engine and Car is a Automobile

    In programming this is represented as:

    class Engine {} // The Engine class.
    
    class Automobile {} // Automobile class which is parent to Car class.
    
    class Car extends Automobile { // Car is an Automobile, so Car class extends Automobile class.
      private Engine engine; // Car has an Engine so, Car class has an instance of Engine class as its member.
    }
    

提交回复
热议问题