When to use Inheritance and Composition

Inheritance defines a new class in terms of an existing class. A subclass inherits both data and behavior from its super class. Object Composition defines a new class as containing an instance of one or more existing classes. We should use Class Inheritance only if instances of the new class can be used in all situations where the existing class can be used.Class Inheritance not inappropriate if the subclass needs to stub out behaviour implemented by the superclass. We should use Object Composition if instances of the new class do not require the protocol of the superclass.

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now