What is composition as it relates to object oriented design?

前端 未结 6 2206
再見小時候
再見小時候 2020-11-28 03:40

I hear (and read on this site) a lot about \"favour composition over inheritance\".

But what is Compositon? I understand inheritance from the point of Person : Mamma

6条回答
  •  清酒与你
    2020-11-28 04:06

    class Engine
    {
    
    }
    
    class Automobile
    {
    
    }
    
    
    class Car extends Automobile // car "is a" automobile //inheritance here
    { 
     Engine engine; // car "has a" engine //composition here
    
    }
    

    Composition - Functionality of an object is made up of an aggregate of different classes. In practice, this means holding a pointer to another class to which work is deferred.

    Inheritance - Functionality of an object is made up of it's own functionality plus functionality from its parent classes.

    As to why composition is preferred over inheritance, take a look at the Circle-ellipse problem.

提交回复
热议问题