# Core OOP Principles

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Object-Oriented JavaScript
Source: https://www.devtutorials.ai/learn/javascript/oop/core-oop-principles

> Encapsulation with public members, private # fields and data hiding; inheritance with parent and child classes and extends; polymorphism through method overriding; and abstraction that hides implementation details behind a small interface.

## What Are the Core OOP Principles?

Four ideas shape how classes are designed and work together:

- **Encapsulation** = protect data.
- **Inheritance** = "is a".
- **Polymorphism** = many behaviours, one method name.
- **Abstraction** = hide details.

**Simple lesson:** keep data safe inside, share common code, let each object answer in its own way, and show only simple controls.

### A Real-World Example

A shop's checkout accepts card, UPI and cash. Each payment class has a `pay()` method that works its own way (polymorphism).
All share a parent `Payment` class (inheritance), keep their secrets in `#private` fields (encapsulation),
and the checkout only ever calls `pay()` (abstraction).

<figure className="ts-fig">
  <svg viewBox="0 0 560 180" role="img" aria-label="A parent class Payment at the top with three children: Card, UPI and Cash. A pay call goes to each child and gets a different answer." width="100%">
    <rect x="0" y="0" width="560" height="180" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="210" y="16" width="140" height="40" rx="8" fill="#1e3a8a" />
    <text x="280" y="41" textAnchor="middle" fontSize="13" fill="#ffffff">Payment</text>
    <line x1="280" y1="56" x2="100" y2="100" stroke="#94a3b8" strokeWidth="2" />
    <line x1="280" y1="56" x2="280" y2="100" stroke="#94a3b8" strokeWidth="2" />
    <line x1="280" y1="56" x2="460" y2="100" stroke="#94a3b8" strokeWidth="2" />
    <rect x="40" y="100" width="120" height="56" rx="8" fill="#eff6ff" stroke="#2563eb" /><text x="100" y="122" textAnchor="middle" fontSize="12" fill="#1e40af">Card</text><text x="100" y="142" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#1e40af">pay(): tap</text>
    <rect x="220" y="100" width="120" height="56" rx="8" fill="#f0fdf4" stroke="#16a34a" /><text x="280" y="122" textAnchor="middle" fontSize="12" fill="#166534">UPI</text><text x="280" y="142" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#166534">pay(): scan</text>
    <rect x="400" y="100" width="120" height="56" rx="8" fill="#fefce8" stroke="#ca8a04" /><text x="460" y="122" textAnchor="middle" fontSize="12" fill="#854d0e">Cash</text><text x="460" y="142" textAnchor="middle" fontSize="11" fontFamily="monospace" fill="#854d0e">pay(): count</text>
    <rect y="96" width="128" height="64" rx="10" fill="none" stroke="#dc2626" strokeWidth="3"><animate attributeName="x" values="36;216;396;36" keyTimes="0;0.33;0.66;1" calcMode="discrete" dur="3s" repeatCount="indefinite" /></rect>
  </svg>
  <figcaption>The children inherit from one parent, and each answers pay() its own way.</figcaption>
</figure>

Two boxes fail on purpose: one reads a private field from outside, one uses `this` before `super()`. Their titles say so.

## What You Will Learn

1. Encapsulation: public and private members, `#` fields, getters.
2. Inheritance: parent and child classes, `extends` and `super`.
3. Polymorphism and method overriding.
4. Abstraction: hiding details and exposing a small interface.

## Encapsulation

### What is encapsulation?

**Encapsulation** = data stays inside the object and changes only through its own methods, which can check every change. Like a bank: you go to the counter, not the vault.

Without it, anyone can break the balance:

```js runnable title="Without encapsulation, anyone can break the balance"
class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
  }
}

const account = new BankAccount("Asha", 500);
account.balance = -5000;

console.log(`${account.owner} has $${account.balance}`);
```

Expected output:

```text
Asha has $-5000
```

### Public members

**Public** = any code can read and change it. In JavaScript, every member is public unless marked private.

```js runnable title="Public members can be used from anywhere"
class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
  }

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

const account = new BankAccount("Ravi", 200);

console.log("Owner:", account.owner);
console.log("After deposit:", account.deposit(50));
console.log("Visible keys:", Object.keys(account));
```

Expected output:

```text
Owner: Ravi
After deposit: 250
Visible keys: [
  "owner",
  "balance"
]
```

### Private members

**Private** = only code inside the class can use it. An underscore (`_balance`) is only a polite habit, not a lock:

```js runnable title="An underscore is a convention, not a lock"
class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this._balance = balance;
  }
}

const account = new BankAccount("Meera", 300);
account._balance = 999999;

console.log("Balance after tampering:", account._balance);
```

Expected output:

```text
Balance after tampering: 999999
```

### Private fields (`#`)

A name starting with `#`, declared at the top of the class body. Only the class can touch it.

```js runnable title="A private #balance, changed only through methods"
class BankAccount {
  #balance = 0;

  constructor(owner, openingDeposit) {
    this.owner = owner;
    this.deposit(openingDeposit);
  }

  deposit(amount) {
    if (amount <= 0) throw new Error("Deposit must be more than zero");
    this.#balance += amount;
    return this.#balance;
  }

  withdraw(amount) {
    if (amount > this.#balance) throw new Error("Not enough money in the account");
    this.#balance -= amount;
    return this.#balance;
  }

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

const account = new BankAccount("Asha", 500);
account.withdraw(120);

console.log("Balance:", account.getBalance());
console.log("Visible keys:", Object.keys(account));

try {
  account.withdraw(10000);
} catch (error) {
  console.log("Refused:", error.message);
}
```

Expected output:

```text
Balance: 380
Visible keys: [
  "owner"
]
Refused: Not enough money in the account
```

Using it from outside is a `SyntaxError`, found before the program even starts:

```js runnable expect-error title="Reading #balance from outside the class is an error"
class BankAccount {
  #balance = 500;
}

const account = new BankAccount();
console.log(account.#balance);
```

**Why "encapsulation"?** The data is sealed inside, like medicine in a capsule.

### Data hiding

A **getter** (`get balance() {...}`) reads like a property but runs a method. With no setter, the value is **read-only** outside.

```js runnable title="A read-only balance through a getter"
class BankAccount {
  #balance = 0;
  #history = [];

  deposit(amount) {
    this.#balance += amount;
    this.#history.push(`+${amount}`);
  }

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

  get transactionCount() {
    return this.#history.length;
  }
}

const account = new BankAccount();
account.deposit(250);
account.deposit(100);

account.balance = 1000000;

console.log("Balance:", account.balance);
console.log("Transactions:", account.transactionCount);
```

Expected output:

```text
Balance: 350
Transactions: 2
```

These boxes run in sloppy mode, so the failed assignment was ignored silently. In strict mode (all modules) it throws a `TypeError`.

### Benefits of encapsulation

- **Valid data:** every change passes a check.
- **One place to look:** a wrong balance must come from the class's own methods.
- **Freedom to change:** the inside can change; outside code still works.
- **Clear instructions:** the public methods show how to use the object.

Default: private data, public methods. Expose data through a getter, and allow changes only where truly needed.

## Inheritance

A manager **is an** employee, so `Manager` can inherit from `Employee`.

### What is inheritance?

**Inheritance** = a new class gets everything from an existing class, then adds its own. Shared code is written once.

### Parent class

The class others inherit from. Also called **base class** or **superclass**.

```js runnable title="Employee, the parent class"
class Employee {
  constructor(name, salary) {
    this.name = name;
    this.salary = salary;
  }

  introduce() {
    return `Hi, I am ${this.name}.`;
  }

  yearlyPay() {
    return this.salary * 12;
  }
}

const asha = new Employee("Asha", 4000);
console.log(asha.introduce());
console.log("Yearly pay:", asha.yearlyPay());
```

Expected output:

```text
Hi, I am Asha.
Yearly pay: 48000
```

### Child class

The class that inherits. Also called **derived class** or **subclass**. Ravi uses `introduce()` though `Manager` never defines it.

```js runnable title="Manager, a child class that adds a team"
class Employee {
  constructor(name, salary) {
    this.name = name;
    this.salary = salary;
  }

  introduce() {
    return `Hi, I am ${this.name}.`;
  }

  yearlyPay() {
    return this.salary * 12;
  }
}

class Manager extends Employee {
  constructor(name, salary, team) {
    super(name, salary);
    this.team = team;
  }

  teamSize() {
    return this.team.length;
  }
}

const ravi = new Manager("Ravi", 6000, ["Asha", "Meera", "Kiran"]);

console.log(ravi.introduce());
console.log("Yearly pay:", ravi.yearlyPay());
console.log("Team size:", ravi.teamSize());
```

Expected output:

```text
Hi, I am Ravi.
Yearly pay: 72000
Team size: 3
```

### `extends` keyword

`class Manager extends Employee` links them. In the child's constructor, `super(...)` runs the parent's constructor, and must come **before** any `this`:

```js runnable expect-error title="Using this before super() is an error"
class Employee {
  constructor(name) {
    this.name = name;
  }
}

class Manager extends Employee {
  constructor(name, team) {
    this.team = team;
    super(name);
  }
}

new Manager("Ravi", ["Asha"]);
```

`instanceof` follows the link one way: every Manager is an Employee, not the reverse.

```js runnable title="A Manager is an Employee"
class Employee {}
class Manager extends Employee {}

const ravi = new Manager();

console.log("Is Ravi a Manager?", ravi instanceof Manager);
console.log("Is Ravi an Employee?", ravi instanceof Employee);
console.log("Is every Employee a Manager?", new Employee() instanceof Manager);
```

Expected output:

```text
Is Ravi a Manager? true
Is Ravi an Employee? true
Is every Employee a Manager? false
```

Inherit only for a true "is a". A `Car` is not an `Engine`; a car **has** an engine, so store one inside it.

## Polymorphism

### What is polymorphism?

**Polymorphism** = different objects answer the **same** method call, each their own way. The cashier says "please pay"; one taps a card, one scans UPI, one hands cash.

```js runnable title="One method name, three different behaviours"
class CardPayment {
  pay(amount) {
    return `Charged $${amount} to the card ending 4242`;
  }
}

class UpiPayment {
  pay(amount) {
    return `Sent $${amount} through UPI to shop@bank`;
  }
}

class CashPayment {
  pay(amount) {
    return `Received $${amount} in cash, change counted`;
  }
}

const payments = [new CardPayment(), new UpiPayment(), new CashPayment()];

for (const payment of payments) {
  console.log(payment.pay(25));
}
```

Expected output:

```text
Charged $25 to the card ending 4242
Sent $25 through UPI to shop@bank
Received $25 in cash, change counted
```

**Why "polymorphism"?** Greek for "many forms".

### Method overriding

**Overriding** = a child writes its own version of an inherited method. `super.method()` calls the parent's version to build on it.

```js runnable title="Manager overrides yearlyPay() and reuses the parent's version"
class Employee {
  constructor(name, salary) {
    this.name = name;
    this.salary = salary;
  }

  yearlyPay() {
    return this.salary * 12;
  }

  describe() {
    return `${this.name} earns $${this.yearlyPay()} a year`;
  }
}

class Manager extends Employee {
  constructor(name, salary, bonus) {
    super(name, salary);
    this.bonus = bonus;
  }

  yearlyPay() {
    return super.yearlyPay() + this.bonus;
  }
}

class Intern extends Employee {
  yearlyPay() {
    return this.salary * 6;
  }
}

const staff = [
  new Employee("Asha", 4000),
  new Manager("Ravi", 6000, 10000),
  new Intern("Kiran", 1500),
];

for (const person of staff) {
  console.log(person.describe());
}
```

Expected output:

```text
Asha earns $48000 a year
Ravi earns $82000 a year
Kiran earns $9000 a year
```

### Benefits of polymorphism

Add a new kind of object without changing the code that uses it, and without long `if` chains that check types.

```js runnable title="A new payment type works with the old loop"
class CardPayment {
  pay(amount) {
    return `Charged $${amount} to the card ending 4242`;
  }
}

class GiftCardPayment {
  constructor(code) {
    this.code = code;
  }
  pay(amount) {
    return `Took $${amount} from gift card ${this.code}`;
  }
}

function checkout(payment, amount) {
  return payment.pay(amount);
}

console.log(checkout(new CardPayment(), 40));
console.log(checkout(new GiftCardPayment("GIFT-2026"), 40));
```

Expected output:

```text
Charged $40 to the card ending 4242
Took $40 from gift card GIFT-2026
```

Code that calls `pay()` works with **every** class that has `pay()`, even classes written later.

## Abstraction

### What is abstraction?

**Abstraction** = a simple way to use an object, without knowing how it works inside. You drive a car with a key, pedals and a wheel, not by firing spark plugs.
Encapsulation protects the data; abstraction picks the simple controls to show.

### Hiding implementation details

**Implementation** = the code that does the real work. Private methods (`#start()`) hide the inner steps behind one public method.

```js runnable title="A car that hides its engine steps"
class Car {
  #fuel = 40;
  #engineRunning = false;

  #checkFuel() {
    if (this.#fuel <= 0) throw new Error("The tank is empty");
  }

  #injectFuel() {
    this.#fuel -= 1;
  }

  #fireSparkPlugs() {
    this.#engineRunning = true;
  }

  start() {
    this.#checkFuel();
    this.#injectFuel();
    this.#fireSparkPlugs();
    return "Engine started";
  }
}

const car = new Car();
console.log(car.start());
console.log("Can the driver fire the spark plugs?", typeof car.fireSparkPlugs);
```

Expected output:

```text
Engine started
Can the driver fire the spark plugs? undefined
```

### Exposing only required functionality

**Interface** = the public methods others may use. Keep it small. A parent class can define the interface, and refuse to be used directly (`new.target`).

```js runnable title="A parent class that defines the interface, and children that fill it in"
class Notifier {
  constructor(recipient) {
    if (new.target === Notifier) {
      throw new Error("Create an EmailNotifier or SmsNotifier, not a Notifier");
    }
    this.recipient = recipient;
  }

  notify(message) {
    return this.send(`Hello ${this.recipient}, ${message}`);
  }

  send(text) {
    throw new Error("Each notifier must provide its own send() method");
  }
}

class EmailNotifier extends Notifier {
  send(text) {
    return `Email: ${text}`;
  }
}

class SmsNotifier extends Notifier {
  send(text) {
    return `SMS: ${text.slice(0, 25)}...`;
  }
}

console.log(new EmailNotifier("Asha").notify("your order has shipped."));
console.log(new SmsNotifier("Ravi").notify("your table is ready at the window."));

try {
  new Notifier("Meera");
} catch (error) {
  console.log("Refused:", error.message);
}
```

Expected output:

```text
Email: Hello Asha, your order has shipped.
SMS: Hello Ravi, your table is...
Refused: Create an EmailNotifier or SmsNotifier, not a Notifier
```

All four together: each class guards its own setup (encapsulation), `EmailNotifier` is a `Notifier` (inheritance), each `notify()` differs (polymorphism), and callers know only `notify()` (abstraction).

## OOP on a Web Page

A checkout uses polymorphism: each payment class has `pay()`, and the page calls it without checking the type. The balance on the wallet is a private field.

```js runnable preview="order-form" title="One checkout, many payment classes"
class Payment {
  constructor(label) {
    this.label = label;
  }
  pay(amount) {
    throw new Error("Each payment type must write its own pay()");
  }
}
class CardPayment extends Payment {
  pay(amount) {
    return `Charged ₹${amount} to the card ending 4242`;
  }
}
class UpiPayment extends Payment {
  pay(amount) {
    return `Sent ₹${amount} through UPI to shop@bank`;
  }
}
class Wallet extends Payment {
  #balance = 500;
  pay(amount) {
    if (amount > this.#balance) return `Wallet has only ₹${this.#balance}`;
    this.#balance -= amount;
    return `Paid ₹${amount} from wallet, ₹${this.#balance} left`;
  }
}

const methods = { S: new CardPayment("Card"), M: new UpiPayment("UPI"), L: new Wallet("Wallet") };
document.querySelector("#size").innerHTML = '<option value="S">Card</option><option value="M" selected>UPI</option><option value="L">Wallet</option>';
document.querySelector("label[for=size]").textContent = "Pay with";

document.querySelector("#order").addEventListener("submit", (event) => {
  event.preventDefault();
  const amount = 149 * Number(document.querySelector("#qty").value);
  const method = methods[document.querySelector("#size").value];
  const message = method.pay(amount);
  document.querySelector("#result").textContent = message;
  console.log(method.label, "→", message);
});
```

Pick **Wallet** and place a few orders. The private balance goes down until it refuses; no code outside the class can change it.

**Easy way to remember:** **E**ncapsulation protects, **I**nheritance shares, **P**olymorphism varies, **A**bstraction hides.

## TL;DR

- `#private` fields and getters protect data; methods check every change.
- `class Child extends Parent`; call `super(...)` before using `this`.
- Override a method in the child; call `super.method()` to reuse the parent's.
- Same method name, different classes: callers need no `if` chains.
- Show a small public interface; hide the steps in private methods.

## Try this

In the method overriding example, add `class Contractor extends Employee` whose `yearlyPay()` returns `this.salary * 10`, and add `new Contractor("Dev", 5000)`. It prints `Dev earns $50000 a year` with no change to `describe()`.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| A public `balance` property | Callers will be careful | Make it `#balance` | Nonsense values get in |
| `_balance` as protection | Underscores lock data | It is only a habit | Outside code still changes it |
| Using `#field` outside the class | Private fields can be read anywhere | Only inside the class | `SyntaxError` |
| `this` before `super()` | Order does not matter | `super()` first | `Must call super constructor...` |
| Overriding without `super.method()` | The parent part still runs | It is replaced | The parent's work is lost |
| `if (type === "card") ... else if ...` | Callers must decide | Each class has the same method | Long chains to update |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `#balance = 0;` in a class body | declare a private field |
| `this.#balance` inside the class | read or change a private field |
| `#checkFuel() { ... }` | a private method, usable only inside the class |
| `get balance() { return this.#balance; }` | a getter, read like a property; read-only if there is no setter |
| `class Manager extends Employee { }` | create a child class that inherits from a parent class |
| `super(name, salary);` | call the parent's constructor, before using `this` |
| `super.yearlyPay()` | call the parent's version of an overridden method |
| a child method with the parent method's name | method overriding |
| `ravi instanceof Employee` | check the "is a" relationship |
| `new.target === Notifier` | inside a constructor, check which class `new` was called with |

</div>

<div className="tscroll">

| Principle | Memory hook | Main tool in JavaScript |
|---|---|---|
| Encapsulation | protect data | private `#` fields, methods that check changes |
| Inheritance | is a | `extends` and `super` |
| Polymorphism | many behaviours | method overriding, the same method name in several classes |
| Abstraction | hide details | private methods and a small public interface |

</div>

## Exercises

## What to Remember

- Protect data, share code, vary behaviour, hide details.
- `extends` + `super` for "is a"; `#` for private.
- Call methods; do not check types.

Next: **DOM Fundamentals**. Find, create, change and remove the elements on a web page.
