Day 17: Object-Oriented Programming in JavaScript

Day 17: Object-Oriented Programming in JavaScript

Welcome back to our JavaScript series! Today, we’ll dive into Object-Oriented Programming (OOP) in JavaScript. OOPs is a programming paradigm that uses objects to represent and manipulate data. It helps in organizing code into reusable and modular pieces. We’ll cover the basics of OOP, including classes, object , inheritance, encapsulation, and polymorphism.

What is Object-Oriented Programming?

Object-Oriented Programming is a programming paradigm centered around objects. An object is a collection of properties and methods. OOP allows you to model real-world entities and their interactions in your code.

Classes and Objects

In ES6, JavaScript introduced classes, which provide a more familiar syntax for creating objects and handling inheritance.

Defining a Class

A class is a blueprint for creating objects. It defines properties and methods that the objects created from the class will have.

Example:

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

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

// Creating an object from the class
const alice = new Person('Alice', 30);
alice.greet(); // Hello, my name is Alice and I am 30 years old.

Inheritance

Inheritance allows one class to inherit properties and methods from another class. This helps in reusing code and creating hierarchical relationships.

Example:

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

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

class Student extends Person {
    constructor(name, age, grade) {
        super(name, age); // Call the parent class constructor
        this.grade = grade;
    }

    study() {
        console.log(`${this.name} is studying and is in grade ${this.grade}.`);
    }
}

const bob = new Student('Bob', 20, 'A');
bob.greet(); // Hello, my name is Bob and I am 20 years old.
bob.study(); // Bob is studying and is in grade A.

Encapsulation

Encapsulation is the practice of keeping the internal state of an object hidden from the outside. This is achieved by using private properties and methods.

Example:

class BankAccount {
    #balance;

    constructor(accountNumber, balance) {
        this.accountNumber = accountNumber;
        this.#balance = balance;
    }

    deposit(amount) {
        if (amount > 0) {
            this.#balance += amount;
        }
    }

    withdraw(amount) {
        if (amount > 0 && amount <= this.#balance) {
            this.#balance -= amount;
        }
    }

    getBalance() {
        return this.#balance;
    }
}

const account = new BankAccount('123456', 1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance()); // 1300

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common super class. It is achieved by method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass.

Example:

class Animal {
    speak() {
        console.log('The animal makes a sound.');
    }
}

class Dog extends Animal {
    speak() {
        console.log('The dog barks.');
    }
}

class Cat extends Animal {
    speak() {
        console.log('The cat meows.');
    }
}

const animals = [new Dog(), new Cat()];

animals.forEach(animal => {
    animal.speak(); // The dog barks. The cat meows.
});

Static Methods

Static methods are called on the class itself, not on instances of the class. They are often used for utility functions.

Example:

class MathUtil {
    static add(a, b) {
        return a + b;
    }

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

console.log(MathUtil.add(5, 3)); // 8
console.log(MathUtil.subtract(5, 3)); // 2

Getters and Setters

Getters and setters allow you to define methods that are called when a property is accessed or modified.

Example:

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

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

    set width(value) {
        if (value > 0) {
            this._width = value;
        }
    }

    get width() {
        return this._width;
    }
}

const rect = new Rectangle(5, 10);
console.log(rect.area); // 50
rect.width = 7;
console.log(rect.area); // 70

Summary

Today, we explored the fundamentals of Object-Oriented Programming in JavaScript. We covered classes and objects, inheritance, encapsulation, polymorphism, static methods, and getters and setters. OOP helps in organizing code, making it more modular, reusable, and easier to maintain. In the coming days, we’ll continue to delve deeper into advanced JavaScript topics. Stay tuned!