DEV Community

Cover image for Class Inheritance
3

Class Inheritance

This blog post will be a brief introduction to inheritance in classes.

To create an instance of a class, we use the new keyword. If we would like to inherit from a base class, then we can use the extends keyword.

class Person {
    name;
    age;

    constructor(name) {
        this.name = name;
        this.age = 33;
    }
    getName() {
        return this.name;
    }
}

// creating new instance of a class Person
const person = new Person("Parwinder");
console.log(person.getName()); // Parwinder

To extend the Person class, let's use extend.

class Person {
    name;
    age;

    constructor(name) {
        this.name = name;
        this.age = 33;
    }
    getName() {
        return this.name;
    }
}

const person = new Person("Parwinder");
console.log(person.getName()); // Parwinder

class Female extends Person {
    gender;
    constructor(name) {
        super(name);
        this.gender = "Female";
    }
}

const female = new Female("Lauren");

console.log(female.getName()); // Lauren
console.log(female instanceof Female); // true
console.log(female instanceof Person); // true

super keyword allows us to use the parent class constructor. We can also use super to call a method from the parent/base class.

Classes in ES6 support:

  • prototypical inheritance,
  • super
  • instance and static methods.

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay