Core OOP Principles

By Syncfusion®, Inc. · Last updated

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).

Payment

Cardpay(): tap UPIpay(): scan Cashpay(): count

The children inherit from one parent, and each answers pay() its own way.

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:

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:

Asha has $-5000

Public members

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

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:

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:

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:

Balance after tampering: 999999

Private fields (#)

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

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:

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:

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.

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:

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.

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:

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.

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:

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:

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.

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:

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.

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:

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.

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:

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.

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:

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.

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:

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).

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:

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.

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: Encapsulation protects, Inheritance shares, Polymorphism varies, Abstraction 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

MistakeWrong ideaCorrect ideaWhat goes wrong
A public balance propertyCallers will be carefulMake it #balanceNonsense values get in
_balance as protectionUnderscores lock dataIt is only a habitOutside code still changes it
Using #field outside the classPrivate fields can be read anywhereOnly inside the classSyntaxError
this before super()Order does not mattersuper() firstMust call super constructor...
Overriding without super.method()The parent part still runsIt is replacedThe parent's work is lost
if (type === "card") ... else if ...Callers must decideEach class has the same methodLong chains to update

Quick reference

SyntaxMeaning
#balance = 0; in a class bodydeclare a private field
this.#balance inside the classread 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 namemethod overriding
ravi instanceof Employeecheck the "is a" relationship
new.target === Notifierinside a constructor, check which class new was called with
PrincipleMemory hookMain tool in JavaScript
Encapsulationprotect dataprivate # fields, methods that check changes
Inheritanceis aextends and super
Polymorphismmany behavioursmethod overriding, the same method name in several classes
Abstractionhide detailsprivate methods and a small public interface

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.