Introduction to Inheritance

Greetings, coder! Our voyage into Object-Oriented Programming (OOP) continues. Today, we will cover Inheritance, which can make our code more efficient and tidy.

Inheritance: First Example

Just as children inherit traits from their parents, child classes in programming inherit behaviors and properties from parent classes.

Below is a practical example displaying a child class inheriting from a parent class:

JavaScript
// Parent class
class Parent {
    constructor(name) {
        this.name = name; // name property
    }

    greet() {
        console.log(`Hello, my name is ${this.name}`); // greet method
    }
}

// 'Child' class extending 'Parent'
class Child extends Parent {
    constructor(name, age) {
        super(name); // call to parent constructor of `Parent`
        this.age = age; // age property
    }

    info() {
        console.log(`I am ${this.age} years old.`); // info method
    }
}

const child = new Child('Alice', 10);
child.greet(); // prints: Hello, my name is Alice
child.info(); // prints: I am 10 years old.

In this example, Child inherits from Parent, so it shares the greet() method, making our code smarter!

Understanding the 'extends' Keyword
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal