TypeScript / TypeScript Classes and Object-Oriented Programming

Implementing Inheritance and Method Overriding

In this tutorial, we will learn about inheritance and method overriding in TypeScript. We will understand how to inherit properties and methods from a parent class and override th…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores object-oriented principles in TypeScript, including classes, inheritance, and access modifiers.

1. Introduction

Goal: The tutorial aims to guide you through the implementation of inheritance and method overriding in TypeScript. You will learn how to inherit properties and methods from a parent class and override these methods in a child class.

What You Will Learn: After completing this tutorial, you will be able to:
- Understand the concept of inheritance and method overriding.
- Implement inheritance in TypeScript.
- Override methods in a child class.

Prerequisites: Familiarity with TypeScript and basic programming concepts such as classes and methods.

2. Step-by-Step Guide

Inheritance is an important concept in object-oriented programming. It allows a class to inherit the properties and methods of another class. The class that is being inherited is called the parent class or superclass, and the class that inherits is called the child class or subclass.

Method Overriding is a feature that allows a child class to provide a different implementation of a method that is already provided by its parent class.

Let's dive into the implementation.

3. Code Examples

3.1 Example 1: Basic Inheritance

// Defining the parent class
class Animal {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    move(distance: number = 0) {
        console.log(`${this.name} moved ${distance}m.`);
    }
}

// Defining the child class
class Dog extends Animal {
    constructor(name: string) {
        super(name);
    }
}

let dog = new Dog("Tommy");
dog.move(10); // Output: Tommy moved 10m.

In this example, the Dog class is inheriting from the Animal class using the extends keyword. The Animal class has a method move which is accessible by the Dog class.

The super keyword is used to call the constructor of the parent class.

3.2 Example 2: Method Overriding

class Animal {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    move(distance: number = 0) {
        console.log(`${this.name} moved ${distance}m.`);
    }
}

class Dog extends Animal {
    constructor(name: string) {
        super(name);
    }

    move(distance = 5) {
        console.log("Running...");
        super.move(distance);
    }
}

let dog = new Dog("Tommy");
dog.move(); // Output: Running... Tommy moved 5m.

In this example, the Dog class overrides the move method of the Animal class. By calling super.move(distance), we can still access the parent class's move method.

4. Summary

  • We learned about inheritance and method overriding in TypeScript.
  • We understood how to inherit properties and methods from a parent class.
  • We saw how to override methods in a child class.
  • Remember, when overriding methods, the super keyword allows us to still access the parent's method.

Next Steps: Explore more about classes in TypeScript. You can start by learning about access modifiers, static properties, and getter and setter methods.

Additional Resources:
- TypeScript Official Documentation

5. Practice Exercises

  1. Create two classes, Person and Employee. The Person class should have properties name and age. The Employee class should inherit from Person and have an additional property salary. Override the toString method to display the employee's details.

  2. Create a Shape class with a method area that returns 0. Then, create Rectangle and Circle classes that inherit from Shape, and override the area method to calculate the area of each shape.

Solutions:

// Exercise 1
class Person {
    constructor(public name: string, public age: number) {}
}

class Employee extends Person {
    constructor(name: string, age: number, public salary: number) {
        super(name, age);
    }

    toString() {
        return `Name: ${this.name}, Age: ${this.age}, Salary: ${this.salary}`;
    }
}

let emp = new Employee("John", 25, 5000);
console.log(emp.toString()); // Output: Name: John, Age: 25, Salary: 5000

// Exercise 2
class Shape {
    area() {
        return 0;
    }
}

class Rectangle extends Shape {
    constructor(public width: number, public height: number) {
        super();
    }

    area() {
        return this.width * this.height;
    }
}

class Circle extends Shape {
    constructor(public radius: number) {
        super();
    }

    area() {
        return Math.PI * this.radius * this.radius;
    }
}

let rect = new Rectangle(5, 10);
console.log(rect.area()); // Output: 50

let circle = new Circle(5);
console.log(circle.area()); // Output: 78.53981633974483

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Date Difference Calculator

Calculate days between two dates.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Image Converter

Convert between different image formats.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help