Science Knowings: JavaScript Course For Social Media

Inheritance in ES6+ Classes

Inheritance in ES6+ Classes

In this session, we delve into Inheritance - a crucial concept in ES6+ classes that enables you to create new classes based on existing ones, inheriting their properties and methods..

What is Inheritance?

Inheritance allows you to define a new class (child class) that inherits the properties and methods of an existing class (parent class).

Benefits of Inheritance

  • Code Reusability
  • Extensibility
  • Reduced Complexity
  • Improved Maintainability

Types of Inheritance

There are several types of inheritance:

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance
  4. Multiple Inheritance
  5. Hybrid Inheritance

Single Inheritance

A child class inherits from a single parent class.

class Child extends Parent {
  // ...
}

Multilevel Inheritance

A child class inherits from a parent class, which itself inherits from another parent class.

class Grandparent {
  // ...
}

class Parent extends Grandparent {
  // ...
}

class Child extends Parent {
  // ...
}

Hierarchical Inheritance

Multiple child classes inherit from a single parent class.

class Parent {
  // ...
}

class Child1 extends Parent {
  // ...
}

class Child2 extends Parent {
  // ...
}

Multiple Inheritance

A child class inherits from multiple parent classes. This is not supported in JavaScript.

Hybrid Inheritance

A combination of different inheritance types, such as single, multilevel, and hierarchical inheritance.

The extends Keyword

The extends keyword is used to establish inheritance between classes.

class Child extends Parent {
  // ...
}

Super Keyword

The super keyword is used to refer to the parent class within the child class.

class Child extends Parent {
  constructor() {
    super();
    // ...
  }
}

Method Overriding

When a child class defines a method with the same name as a method in the parent class, it overrides the parent's method.

class Child extends Parent {
  greet() {
    // Override the greet method of the parent class
  }
}

Abstract Classes

Abstract classes are classes that cannot be instantiated directly but serve as templates for creating subclasses.

abstract class Shape {
  abstract getArea();
}

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass.

class Animal {
  speak() {
    // ...
  }
}

class Dog extends Animal {
  speak() {
    console.log('Woof!');
  }
}

class Cat extends Animal {
  speak() {
    console.log('Meow!');
  }
}

Next Topic: Method Chaining

Method chaining is a technique that allows you to perform multiple operations on an object in a single statement. Join us next time to learn the how and why of method chaining in ES6+.