你的评论

My answer: Flexibility.

Background

This is how I understand Inheritance and Composition:

  • Inheritance is an "is-a" relationship.
  • Composition is a "has-a" relationship.

Explain

It's easier to compose an object that does something ("has-a") than extends what it is ("is-a"). That is, inheritance strongly couples the child class with its parent class, and you always need to make sure the new code only extends the parent correctly. On contrast, composition allows you to move or add code more easily as you don't need to worry about failing to be a proper child class.

Usually, they both look good when you introduce some new classes; however, you will soon find out the composition code is much easier to modify when you make new changes.

It is possible to live without inheritance. The book "The Pragmatic Programmer" has a section about how to eliminate them entirely.

Reference

Here are some good references of this topic.



UserEcho 的客户支持