Understanding TypeScript Inheritance
Inheritance in TypeScript
Welcome back! Now that you have a solid understanding of classes and objects, it's time to delve deeper into inheritance. This is a natural progression in our journey into object-oriented programming (OOP) using TypeScript's class-based system—meaning we use classes as blueprints to create and organize objects and their behaviors.
Inheritance in TypeScript allows you to create a new class that reuses the behavior of an existing class. This facilitates code reuse, extends object functionalities, and helps you create easily manageable and understandable programs. Let's dive in!
What We'll Cover
In this lesson, you'll learn how to leverage inheritance in TypeScript. We'll cover:
- What Inheritance Is in TypeScript
- How to Implement Inheritance Using Classes
- Benefits of Using Inheritance
You'll also learn about class hierarchies and how to manage inheritance using constructors and class features.
What Inheritance Is
Inheritance in TypeScript is a mechanism to create a hierarchical class structure, where one class inherits the properties and methods of another. To better understand this, we’ll use an example involving a Person class as the base class and a Student class as the derived class. This will help you see how properties and methods are inherited and extended in TypeScript.
Base Class: Person
Derived Class: Student
Now, we’ll create a Student class that extends the Person class:
In the Student class, we use the extends keyword to inherit from Person. The constructor uses the super function to call the base class constructor, initializing the inherited properties. The Student class adds a new attribute, major, and a displayMajor method specific to its class.
