Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 9: Modern OOP (Classes)

1. The Class Syntax

A class is a blueprint for creating objects. It encapsulates data (properties) and behavior (methods) into a single unit.

JavaScript

class Player {
    // The constructor runs automatically when 'new' is called
    constructor(name, level) {
        this.name = name;
        this.level = level;
    }

    // This is a Method (automatically placed on Player.prototype)
    levelUp() {
        this.level++;
        console.log(`${this.name} is now level ${this.level}!`);
    }
}

const p1 = new Player("Aragon", 10);
p1.levelUp(); // "Aragon is now level 11!"

2. Inheritance with extends and super

One of the biggest advantages of classes is how easily they handle inheritance. You can create a “Child” class that inherits everything from a “Parent” class.

  • extends: Links the child’s prototype to the parent’s prototype.
  • super(): A special function that calls the constructor of the parent class. It must be called before using this in a child constructor.

JavaScript

class Character {
    constructor(name) {
        this.name = name;
        this.health = 100;
    }
}

class Mage extends Character {
    constructor(name, spell) {
        super(name); // Calls Character constructor
        this.spell = spell;
    }

    cast() {
        console.log(`${this.name} casts ${this.spell}!`);
    }
}

const gandalf = new Mage("Gandalf", "Fireball");
console.log(gandalf.health); // 100 (Inherited)
gandalf.cast(); // "Gandalf casts Fireball!"

3. Getters and Setters

Getters and setters allow you to define methods that look like properties. This is useful for data validation or computed properties.

JavaScript

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

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

    // Setter
    set width(value) {
        if (value <= 0) console.error("Width must be positive!");
        else this._width = value;
    }
}

const rect = new Rectangle(10, 5);
console.log(rect.area); // 50 (Accessed like a property, not rect.area())

4. Static Methods and Properties

Static members belong to the class itself, not to the instances (objects) created from the class. They are often used for utility functions.

JavaScript

class MathHelper {
    static pi = 3.14;

    static calculateCircleArea(radius) {
        return this.pi * radius * radius;
    }
}

console.log(MathHelper.pi); // 3.14
// const helper = new MathHelper(); 
// helper.calculateCircleArea(5); // Error! Not a function on the instance.

5. Private Fields (#)

Historically, JS developers used underscores (e.g., _password) to signal that a property was private. Now, JavaScript has native private fields using the # symbol. These cannot be accessed outside the class.

JavaScript

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

    constructor(owner) {
        this.owner = owner;
    }

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

    showBalance() {
        console.log(`Balance for ${this.owner}: $${this.#balance}`);
    }
}

const myAcc = new BankAccount("John");
myAcc.deposit(500);
// console.log(myAcc.#balance); // Syntax Error: Private field must be accessed within class
myAcc.showBalance(); // Works!

In Simple Words

1. Introduction to Modern OOP

Modern Object-Oriented Programming (OOP) uses classes as blueprints to create objects that model real-world entities.

Classes provide:

  • Structure
  • Reusability
  • Maintainability
  • Scalability

Even in JavaScript, classes are a clean abstraction over prototypes.


2. What is a Class?

Definition

A class is a blueprint that defines:

  • Properties (data)
  • Methods (behavior)

Example (conceptual):

class User {
   name
   login()
}

3. Object vs Class

AspectClassObject
MeaningBlueprintInstance
MemoryNo dataActual data
Created usingclassnew

4. Creating Classes

Basic Structure

class ClassName {
   constructor() {}
   method() {}
}

Constructor

  • Special method
  • Runs when object is created
  • Initializes properties

5. Properties (Fields)

Instance Properties

  • Belong to object
  • Each object has its own copy

Static Properties

  • Belong to class
  • Shared across objects

6. Methods

Instance Methods

  • Called using object
  • Access instance data via this

Static Methods

  • Called using class name
  • Utility/helper behavior

7. Access Modifiers

Common Modifiers

  • public
  • private
  • protected

Used to implement encapsulation.


8. Encapsulation in Classes

Encapsulation ensures:

  • Data hiding
  • Controlled access
  • Validation logic

Example (conceptual):

private balance
public deposit()

9. Inheritance

What is Inheritance?

Inheritance allows a class to reuse and extend another class.


extends Keyword

class Admin extends User

super Keyword

  • Calls parent constructor
  • Access parent methods

10. Method Overriding

  • Child class redefines parent method
  • Enables polymorphism

11. Polymorphism

Definition

Polymorphism allows:

Same method name → different behavior

Achieved via:

  • Method overriding
  • Method overloading (language-dependent)

12. Abstraction

What is Abstraction?

Hiding implementation details and showing only essential features.

Implemented using:

  • Abstract classes
  • Interfaces

13. Abstract Classes

  • Cannot be instantiated
  • May contain abstract + concrete methods
  • Acts as base class

14. Interfaces

  • Define contracts
  • No implementation (mostly)
  • Multiple inheritance supported

15. Composition vs Inheritance

AspectInheritanceComposition
Relationship“is-a”“has-a”
FlexibilityLowHigh
CouplingTightLoose

👉 Modern OOP prefers composition.


16. Method Chaining

Returning this enables chained calls.

Example:

user.setName().setAge().save()

17. Immutability & OOP

  • Prevents side effects
  • Improves predictability
  • Common in modern design

18. Class Lifecycle

  1. Class definition
  2. Object creation
  3. Constructor execution
  4. Method calls
  5. Object destruction / GC

19. Common OOP Design Patterns

  • Singleton
  • Factory
  • Builder
  • Strategy
  • Observer

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥