What is composition as it relates to object oriented design?

前端 未结 6 2213
再見小時候
再見小時候 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:05

    There are three ways to give behavior to a class. You can write that behavior into the class; you can inherit from a class that has the desired behavior; or you can incorporate a class with the desired behavior into your class as a field, or member variable. The last two represent forms of code reuse, and the final one - composition - is generally preferred. It doesn't actually give your class the desired behavior - you still need to call the method on the field - but it puts fewer constraints on your class design and results in easier to test and easier to debug code. Inheritance has its place, but composition should be preferred.

提交回复
热议问题