JavaScript Classes and Inheritance

Introduction to Classes

Classes in JavaScript provide a way to create reusable, blueprints for objects. They encapsulate data for the object to work with and methods to perform operations.

Try yourself
        
            
// Example of Classes
class Person {
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    getFullName() {
        return `${this.firstName} ${this.lastName}`;
    }
}

const johnDoe = new Person('John', 'Doe');
const fullName = johnDoe.getFullName(); // Result: John Doe

        
    

Creating a Class

To create a class, you use the class keyword, followed by the name of the class.

Try yourself
        
            
class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

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

        
    

Constructor Method

The constructor method is called automatically when a new instance of a class is created. It's used to initialize class properties.

Try yourself
        
            
class Car {
    constructor(brand, model) {
        this.brand = brand;
        this.model = model;
    }

    startEngine() {
        console.log(`Starting the ${this.brand} ${this.model}...`);
    }
}

        
    

Class Methods

Methods are functions defined within a class and are used to perform actions related to the class.

Try yourself
        
            
class Calculator {
    add(a, b) {
        return a + b;
    }

    subtract(a, b) {
        return a - b;
    }

    multiply(a, b) {
        return a * b;
    }

    divide(a, b) {
        return a / b;
    }
}

        
    

Creating Instances

To use a class, you need to create an instance of it. This is done with the new keyword.

Try yourself
        
            
class Product {
    constructor(name, price) {
        this.name = name;
        this.price = price;
    }

    displayInfo() {
        console.log(`Product: ${this.name}, Price: $${this.price}`);
    }
}

const laptop = new Product('Laptop', 1200);
const phone = new Product('Phone', 800);

        
    

Inheritance

Inheritance is a fundamental concept in object-oriented programming. It allows one class to inherit properties and methods from another class.

Try yourself
        
            
class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        console.log(`${this.name} makes a sound.`);
    }
}

class Dog extends Animal {
    speak() {
        console.log(`${this.name} barks.`);
    }
}

        
    

Extending a Class

To inherit from another class, you use the extends keyword. The subclass can then use the properties and methods of the parent class.

Try yourself
        
            
class Shape {
    constructor(color) {
        this.color = color;
    }

    getColor() {
        return this.color;
    }
}

class Circle extends Shape {
    constructor(color, radius) {
        super(color);
        this.radius = radius;
    }

    getArea() {
        return Math.PI * Math.pow(this.radius, 2);
    }
}

        
    

Overriding Methods

Inheritance allows you to override methods from the parent class in the child class, providing custom behavior.

Try yourself
        
            
class Vehicle {
    start() {
        console.log('Vehicle is starting...');
    }
}

class Car extends Vehicle {
    start() {
        super.start();
        console.log('Car engine is running.');
    }
}

        
    

Super Keyword

The super keyword is used to call the parent class's constructor or methods.

Try yourself
        
            
class Parent {
    constructor(name) {
        this.name = name;
    }

    sayHello() {
        console.log(`Hello, I'm ${this.name}`);
    }
}

class Child extends Parent {
    sayHello() {
        super.sayHello();
        console.log('And I am a child.');
    }
}

        
    

Using Classes in Practice

Let's put what we've learned into practice by creating a simple example.

Try yourself
        
            
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greet() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
    }
}

const john = new Person('John Doe', 30);
john.greet();

        
    

Summary

Classes and inheritance are powerful tools in JavaScript for creating reusable and organized code. Understanding how to define classes, use constructors, create methods, and apply inheritance will greatly enhance your ability to build complex applications.