Composition VS Inheritance

What are they?

So what are composition and inheritance? Below you will find WikipediasWikipedias definition of them both.

So which is better?

The biggest difference between the two is the way the objects relate to each other. For example in inheritance, the bus is the vehicle and in composition, the bus has a steering wheel. With inheritance, you have to be careful when changing the base class because it can cause some problems in your code. With composition, you have more flexibility when changing parts in your base code also can allow you to change behavior and runtime. Composition makes it easier to combine components because there is more commonality between the class tree.

Conclusion

Like everything with software development, we look at use case. Everything comes with pros and cons, most the time composition can substitue inheritance but it doesn’t always work. In most cases ask yourself would it make more sences to use composition and as long as your not making specialized sub or superclasses if the answer is no then you should use inheritance.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store