Inheritance and Composition
Inheritance and Composition#
Inheritance and Composition in TypeScript#
As we plan and organize the various classes of a program, we may discover a hierarchy of classes that share some functionality. For example, we may have a base
Product class and two classes
PhysicalProduct that share code with the base class. Inheritance solves this problem by allowing classes to inherit methods and properties from a base class. To inherit these methods and properties, we use the extends keyword. In TypeScript, a class can extend at most one other class.
Below we define a
Product class that can print its display name through a
Below we implement two classes that extend
Product, they can make use of the
printDisplayName() method inherited from the base class:
Benefits of Inheritance#
The primary benefit of inheritance is that it helps us reuse shared logic and data. Inheritance may be a good fit when there is a clear hiearchical relationship between the parent and child classes.
As our app grows over time, we may hit an issue with inheritance: the tight coupling between a parent class and its children makes the parent class resistant to change. The parent class is fragile because changing its code could result in unexpected behavior in the child classes (a parent class has no idea how its children are using the base code, so it is hard to make assumptions about downstream impacts of code changes).