JavaScript Classes & OOP: Encapsulation, Inheritance & Private Fields

Introduced in ECMAScript 2015 (ES6), Classes bring a clean, formal syntax to Object-Oriented Programming (OOP) in JavaScript. They cleanly encapsulate properties, methods, inheritance (extends), parent calls (super), and private state (#).

Class Declaration & Methods

class User {
    // 1. Constructor Method (Runs upon instantiation with 'new')
    constructor(username, email) {
        this.username = username;
        this.email = email;
    }

    // 2. Instance Method (Stored on User.prototype)
    displayInfo() {
        return `User: ${this.username} (${this.email})`;
    }

    // 3. Static Method (Called directly on Class, not on instances!)
    static compareUsers(u1, u2) {
        return u1.username === u2.username;
    }
}

const user1 = new User("vikram", "v@v.com");
console.log(user1.displayInfo()); // "User: vikram (v@v.com)"
console.log(User.compareUsers(user1, user1)); // true

Inheritance with extends & super()

// Parent Class
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        return `Hello, I am ${this.name}`;
    }
}

// Child Class extending Person
class Student extends Person {
    constructor(name, age, rollNo, semester) {
        // super() invokes parent constructor; mandatory before accessing 'this'!
        super(name, age);
        this.rollNo = rollNo;
        this.semester = semester;
    }

    // Method Overriding
    greet() {
        return `${super.greet()}, studying in Semester ${this.semester}.`;
    }
}

const bcaStudent = new Student("Pooja", 20, 108, 4);
console.log(bcaStudent.greet()); // "Hello, I am Pooja, studying in Semester 4."

Modern Encapsulation: Private Fields (#)

Introduced in ES2022, private fields provide true language-level encapsulation:

class BankAccount {
    // Private field declaration
    #balance = 0;

    constructor(initialDeposit) {
        this.#balance = initialDeposit;
    }

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

    // Getter Method
    get balance() {
        return this.#balance;
    }
}

const myAccount = new BankAccount(10000);
myAccount.deposit(2500);
console.log("Verified Balance:", myAccount.balance); // 12500

// Direct access throws SyntaxError!
// console.log(myAccount.#balance); // SyntaxError: Private field '#balance' must be declared!

University Exam Corner (BCA Examination Notes)

Exam Question: "What are the 4 fundamental pillars of OOP in JavaScript?"

  • Encapsulation: Bundling data and methods together and hiding internal state using private fields (#).
  • Inheritance: Creating specialized subclasses using extends and super.
  • Polymorphism: Subclasses overriding parent methods to provide specialized behavior.
  • Abstraction: Exposing clean, high-level interfaces while concealing implementation complexity.

Next Step

How does JavaScript coordinate synchronous code, Promises, and timers without blocking? Proceed to: JavaScript Event Loop: Concurrency & Microtasks →

Explore Related JavaScript Tutorials

Accelerate your JavaScript mastery by studying these tightly connected core tutorials:

Prototypes & Delegation →

Underlying prototype mechanism of classes.

The this Keyword →

Instance references in constructor and methods.

ES Modules →

Exporting and importing class definitions.

Object Fundamentals →

Instance properties and memory layout.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!