Inheritance in TypeScript classes
Introduction
Hello again! In this part of our journey into Object-Oriented Programming with TypeScript, we'll explore inheritance. Inheritance allows us to share code across classes, thus improving readability and efficiency.
TypeScript enhances this process with strong typing, which ensures reliability and consistent behavior across the application. By leveraging TypeScript's type system, we can reinforce the integrity of our inherited attributes and methods, providing a more robust programming experience.
In this lesson, we'll explore attribute and method inheritance in TypeScript using practical examples. Our lesson plan includes defining inheritance, examining attribute inheritance, exploring method inheritance, and understanding the super() function. Ready? Let's get started!
Defining Inheritance
Inheritance involves creating a child class that inherits properties and methods from a parent class. In TypeScript, we encounter scenarios where classes share common attributes or methods, making inheritance highly useful.
The extends keyword is used to set up inheritance, allowing one class to inherit properties and methods from another class. Here's an example featuring a parent class named Vehicle and a child class named Car, both using TypeScript syntax:
In the Car class, the super() function inside its constructor calls the Vehicle class's constructor, enabling the inherited properties to be correctly initialized. The extends keyword signifies that Car is a subclass of Vehicle.
In this lesson, our focus will primarily be on single inheritance, where one parent class gives attributes and methods to one child class, highlighting the strengths of type-safe inheritance in TypeScript.
Attribute Inheritance
Attribute inheritance allows a child class to inherit the attributes of a parent class, with private fields being protected by TypeScript's access modifiers.
Consider this example featuring a parent class named Artist, and a child class named Musician:
However, if the name attribute in the Artist class were private, it wouldn't be directly accessible in the Musician class. Instead, it would be accessed via a method:
The Musician class inherits the name attribute from the Artist class and also has its own unique attribute, instrument. Since name is private, it is accessed through the getName method.
