OOP Principles in JavaScript: Encapsulation, Abstraction, Inheritance, Polymorphism

“Explain the four pillars of OOP” is one of the most common interview questions for testers and developers, and the answer matters in practice too: well-designed test frameworks use exactly these ideas to stay readable as they grow to hundreds of tests. In this lesson you will see encapsulation, abstraction, inheritance and polymorphism in JavaScript code, learn JavaScript-specific ideas such as duck typing and mixins, get a first look at the SOLID principles, and finish with a reporter design that uses all four pillars.

Advertisement

📖 What You’ll Learn: the four pillars of object-oriented programming, encapsulation with private fields, abstraction with simple public interfaces, inheritance with extends, polymorphism through method overriding and duck typing, mixins, composition, an introduction to SOLID, and a pluggable test reporter that applies everything.


🏛️ The Four Pillars of OOP

Definition: object-oriented programming (OOP) organises code around objects that combine data (properties) and behaviour (methods). Four principles describe how good object-oriented code is structured:

PillarIn one sentenceJavaScript tools
EncapsulationKeep an object’s data and the code that changes it together, and hide the internals#private fields, getters/setters, closures
AbstractionExpose a simple interface and hide the complex details of how it worksPublic methods with clear names; private helper methods
InheritanceLet a class reuse and extend another classextends, super, prototypes
PolymorphismUse different objects through the same interface, each behaving in its own wayMethod overriding, duck typing

The earlier lessons in this module taught the syntax: classes, inheritance and private fields. This lesson is about why and when to use them.


🔒 Encapsulation

Definition: encapsulation means bundling data with the methods that operate on it, and restricting direct access to the data so it can only change in controlled ways.

📄 encapsulation.js

class BankAccount {
  #balance = 0;                 // hidden state
  #history = [];

  deposit(amount) {
    if (amount <= 0) throw new Error("Deposit must be positive");
    this.#balance += amount;
    this.#history.push(`+${amount}`);
  }

  withdraw(amount) {
    if (amount > this.#balance) throw new Error("Insufficient funds");
    this.#balance -= amount;
    this.#history.push(`-${amount}`);
  }

  get balance() { return this.#balance; }        // read-only view
  get history() { return [...this.#history]; }  // a copy, so callers cannot change it
}

const acc = new BankAccount();
acc.deposit(500);
acc.withdraw(120);
console.log(acc.balance, acc.history);

acc.history.push("+1000000");   // only changes the copy
acc.balance = 1e9;               // ignored: getter only (sloppy mode outside the class)
console.log(acc.balance, acc.history);

⌨️ Terminal

node encapsulation.js

🖥️ Output

380 [ '+500', '-120' ]
380 [ '+500', '-120' ]

Every rule (no negative deposits, no overdrafts) is enforced in one place. No outside code can put the account into an invalid state, which is the real goal of encapsulation.


🎭 Abstraction

Definition: abstraction means exposing only what callers need (the “what”) and hiding how it is done (the “how”). Callers depend on a small, stable interface, so the internals can change without breaking them.

📄 abstraction.js

class EmailService {
  send(to, subject) {                          // the whole public interface
    this.#validate(to);
    const message = this.#build(to, subject);
    return this.#deliver(message);
  }

  #validate(to) {
    if (!to.includes("@")) throw new Error(`Bad address: ${to}`);
  }
  #build(to, subject) {
    return { to, subject, headers: { "x-mailer": "sqa-mailer/1.0" } };
  }
  #deliver(message) {                          // could switch from SMTP to an API without callers noticing
    return `queued "${message.subject}" for ${message.to}`;
  }
}

const mail = new EmailService();
console.log(mail.send("asha@sqatools.in", "Nightly report"));
console.log(Object.getOwnPropertyNames(EmailService.prototype));   // only send is public

⌨️ Terminal

node abstraction.js

🖥️ Output

queued "Nightly report" for asha@sqatools.in
[ 'constructor', 'send' ]

💡 Tip: Page objects are abstraction in action: a test calls loginPage.login(user) and does not care which selectors, waits or clicks happen inside. When the login form changes, only the page object changes.


Advertisement

🌳 Inheritance

Definition: inheritance lets a class reuse the code of a more general class and add or change behaviour. Use it for genuine “is a” relationships and keep hierarchies shallow.

📄 inheritance.js

class Notification {
  constructor(recipient) { this.recipient = recipient; }
  format(text) { return `To ${this.recipient}: ${text}`; }
  send(text) { return `[${this.constructor.name}] ${this.format(text)}`; }
}

class SmsNotification extends Notification {
  format(text) { return super.format(text).slice(0, 40); }   // SMS has a length limit
}

class SlackNotification extends Notification {
  format(text) { return `${super.format(text)} :white_check_mark:`; }
}

console.log(new SmsNotification("+91 98765 43210").send("Build 4512 passed all 1,204 tests in 18 minutes"));
console.log(new SlackNotification("#qa-alerts").send("Build 4512 passed"));

⌨️ Terminal

node inheritance.js

🖥️ Output

[SmsNotification] To +91 98765 43210: Build 4512 passed al
[SlackNotification] To #qa-alerts: Build 4512 passed :white_check_mark:

Both subclasses reuse send from the parent and change only the part that differs.


🔀 Polymorphism

Definition: polymorphism (“many forms”) means code can work with objects of different types through the same interface, and each object responds in its own way. The calling code does not need if/else or switch on the type.

📄 polymorphism.js

class Shape { area() { return 0; } }
class Circle extends Shape {
  constructor(r) { super(); this.r = r; }
  area() { return Math.PI * this.r ** 2; }
}
class Rect extends Shape {
  constructor(w, h) { super(); this.w = w; this.h = h; }
  area() { return this.w * this.h; }
}

const shapes = [new Circle(1), new Rect(2, 3), new Circle(2)];
for (const s of shapes) {
  console.log(s.constructor.name.padEnd(7), s.area().toFixed(2));   // same call, different behaviour
}
console.log("total:", shapes.reduce((sum, s) => sum + s.area(), 0).toFixed(2));

⌨️ Terminal

node polymorphism.js

🖥️ Output

Circle  3.14
Rect    6.00
Circle  12.57
total: 21.71

Duck typing

JavaScript does not require a shared parent class for polymorphism. If an object has the method you call, it works: “if it walks like a duck and quacks like a duck, it is a duck”. This is called duck typing.

📄 duck-typing.js

const consoleLogger = { log: (m) => `console: ${m}` };
const fileLogger = { log: (m) => `file: ${m}` };
class JsonLogger { log(m) { return JSON.stringify({ level: "info", m }); } }

function runWithLogger(logger) {
  return logger.log("test started");     // only needs a log method
}

for (const logger of [consoleLogger, fileLogger, new JsonLogger()]) {
  console.log(runWithLogger(logger));
}

try {
  runWithLogger({ write: () => "wrong shape" });
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node duck-typing.js

🖥️ Output

console: test started
file: test started
{"level":"info","m":"test started"}
TypeError: logger.log is not a function

Playwright reporters work this way: any object with methods such as onTestEnd and onEnd can be a reporter, without extending a framework class.


Advertisement

🧩 Mixins and Composition

JavaScript classes can extend only one parent. To share behaviour across unrelated classes, use composition (an object holds helpers, see the Inheritance lesson) or a mixin: a function that takes a class and returns a subclass with extra methods.

📄 mixins.js

const Timestamped = (Base) => class extends Base {
  stamp() { return `${this.constructor.name} at 2026-11-23T10:00:00Z`; }
};
const Serializable = (Base) => class extends Base {
  serialize() { return JSON.stringify(this); }
};

class TestResult {
  constructor(name, passed) { this.name = name; this.passed = passed; }
}

class RichResult extends Serializable(Timestamped(TestResult)) {}

const r = new RichResult("login", true);
console.log(r.serialize());
console.log(r.stamp(), r instanceof TestResult);

⌨️ Terminal

node mixins.js

🖥️ Output

{"name":"login","passed":true}
RichResult at 2026-11-23T10:00:00Z true

⚠️ Watch out: Stacking many mixins makes it hard to see where a method comes from. Prefer composition for most cases, and keep mixins small and focused.


🧱 A First Look at SOLID

SOLID is a set of five design principles that build on the four pillars. Test framework code benefits from them as much as application code:

PrincipleMeaningTest-framework example
Single responsibilityA class should have one reason to changeA page object handles one page; an API client handles one service
Open/closedOpen for extension, closed for modificationAdd a new reporter without editing the runner
Liskov substitutionSubclasses must work wherever the parent worksAny BasePage subclass supports open()
Interface segregationPrefer small, focused interfacesSeparate Clickable and Typeable component helpers
Dependency inversionDepend on abstractions, inject dependenciesPass page or an API client into constructors instead of creating them inside

The Playwright course covers these in depth in SOLID Principles with Playwright.


🧪 Tester Scenario: A Pluggable Test Reporter

This design uses all four pillars. The runner (abstraction) hides how tests are executed and keeps results private (encapsulation). Reporters share a base class (inheritance) and the runner calls each one through the same methods (polymorphism), so adding a new output format never requires changing the runner (open/closed principle).

📄 reporter.js

class Reporter {
  onTestEnd(result) {}
  onEnd(summary) {}
}

class ConsoleReporter extends Reporter {
  onTestEnd(r) { console.log(`  ${r.passed ? "✓" : "✗"} ${r.name}`); }
  onEnd(s) { console.log(`  ${s.passed}/${s.total} passed`); }
}

class JsonReporter extends Reporter {
  #results = [];
  onTestEnd(r) { this.#results.push(r); }
  onEnd(s) { console.log("  json:", JSON.stringify({ ...s, failures: this.#results.filter((r) => !r.passed).map((r) => r.name) })); }
}

const slackReporter = {                           // duck-typed: no base class needed
  onTestEnd() {},
  onEnd: (s) => console.log(`  slack: ${s.failed === 0 ? "all green" : `${s.failed} failing`}`),
};

class Runner {
  #tests = [];
  #reporters;
  constructor(reporters) { this.#reporters = reporters; }        // dependency injection
  add(name, fn) { this.#tests.push({ name, fn }); return this; }
  run() {
    let passed = 0;
    for (const { name, fn } of this.#tests) {
      let ok = true;
      try { fn(); } catch { ok = false; }
      if (ok) passed++;
      this.#reporters.forEach((rep) => rep.onTestEnd({ name, passed: ok }));
    }
    const summary = { total: this.#tests.length, passed, failed: this.#tests.length - passed };
    this.#reporters.forEach((rep) => rep.onEnd(summary));
  }
}

new Runner([new ConsoleReporter(), new JsonReporter(), slackReporter])
  .add("login works", () => {})
  .add("cart total", () => { if (10 + 20 !== 30) throw new Error(); })
  .add("checkout", () => { throw new Error("500 from payment API"); })
  .run();

⌨️ Terminal

node reporter.js

🖥️ Output

  ✓ login works
  ✓ cart total
  ✗ checkout
  2/3 passed
  json: {"total":3,"passed":2,"failed":1,"failures":["checkout"]}
  slack: 1 failing

Playwright’s real reporter API follows the same idea: you list reporters in playwright.config, and each receives the same events.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write a class Thermostat that encapsulates a private temperature, allows changes only through increase() and decrease(), and never goes below 10 or above 30.

Show answer

📄 practice1.js

class Thermostat {
  #temp = 20;
  increase() { this.#temp = Math.min(30, this.#temp + 1); return this; }
  decrease() { this.#temp = Math.max(10, this.#temp - 1); return this; }
  get temperature() { return this.#temp; }
}
const t = new Thermostat();
for (let i = 0; i < 15; i++) t.increase();
console.log(t.temperature);
for (let i = 0; i < 30; i++) t.decrease();
console.log(t.temperature);

🖥️ Output

30
10

Q2. Create Employee with pay(), and subclasses FullTime (monthly salary) and Contractor (hours × rate) that override it. Print the total payroll for a mixed list.

Show answer

📄 practice2.js

class Employee {
  constructor(name) { this.name = name; }
  pay() { return 0; }
}
class FullTime extends Employee {
  constructor(name, salary) { super(name); this.salary = salary; }
  pay() { return this.salary; }
}
class Contractor extends Employee {
  constructor(name, hours, rate) { super(name); this.hours = hours; this.rate = rate; }
  pay() { return this.hours * this.rate; }
}
const staff = [new FullTime("Asha", 90000), new Contractor("Ravi", 120, 600), new FullTime("Meera", 75000)];
console.log(staff.reduce((sum, e) => sum + e.pay(), 0));

🖥️ Output

237000

Q3. Use duck typing: write describeAll(items) that prints item.describe() for every item that has a describe method and skips the others.

Show answer

📄 practice3.js

function describeAll(items) {
  for (const item of items) {
    if (typeof item?.describe === "function") console.log(item.describe());
  }
}
describeAll([
  { describe: () => "a plain object" },
  new (class Book { describe() { return "a Book instance"; } })(),
  { name: "no describe method" },
  null,
]);

🖥️ Output

a plain object
a Book instance

Q4. Write a mixin Countable that adds a static created counter incremented in the constructor, and apply it to a class Order.

Show answer

📄 practice4.js

const Countable = (Base) => class extends Base {
  static created = 0;
  constructor(...args) {
    super(...args);
    this.constructor.created++;
  }
};
class Order extends Countable(class {}) {}
new Order(); new Order(); new Order();
console.log(Order.created);

🖥️ Output

3

Q5. Which OOP pillar does each describe? (a) a page object hides selectors behind login(); (b) #token cannot be read outside the class; (c) AdminPage extends BasePage; (d) the runner calls onEnd() on any reporter.

Show answer

(a) Abstraction, (b) Encapsulation, (c) Inheritance, (d) Polymorphism.

Q6. Refactor this switch into polymorphism: each payment method should be an object with a fee(amount) method.

function fee(method, amount) {
  switch (method) {
    case "card": return amount * 0.02;
    case "upi": return 0;
    case "wallet": return amount * 0.01;
  }
}
Show answer

📄 practice6.js

const methods = {
  card: { fee: (amount) => amount * 0.02 },
  upi: { fee: () => 0 },
  wallet: { fee: (amount) => amount * 0.01 },
};
for (const [name, method] of Object.entries(methods)) {
  console.log(name, method.fee(1000));
}

🖥️ Output

card 20
upi 0
wallet 10

Adding a new payment method now means adding one object, without touching existing code (open/closed principle).


🧠 MCQ Quiz: OOP Principles

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. Which pillar is about hiding internal state and controlling changes to it?
  2. Which pillar lets the same method call behave differently for different objects?
  3. A page object exposes login(user) and hides its selectors. Which pillar is that mainly?
  4. What is duck typing?
  5. How many classes can a JavaScript class extend directly?
  6. What is a mixin in JavaScript?
  7. What does the “O” in SOLID stand for?
  8. Why return a copy from a getter like get history()?
  9. What is dependency injection?
  10. Which is the best sign you should use composition instead of inheritance?

💼 Interview Questions and Answers

Q1. Explain the four pillars of OOP with JavaScript examples.

  • Encapsulation: a BankAccount keeps #balance private and changes it only through deposit/withdraw, which validate input.
  • Abstraction: a LoginPage.login(user) method hides selectors, waits and clicks behind one intent-based call.
  • Inheritance: class CartPage extends BasePage reuses open() and navigation helpers.
  • Polymorphism: a test runner calls reporter.onEnd(summary) on console, JSON and HTML reporters, and each produces its own output.

Q2. What is the difference between abstraction and encapsulation?

Abstraction is about design: deciding what a caller needs to know and offering a simple interface (what the object does). Encapsulation is about protection: bundling data with its methods and restricting access to the data (how the object keeps its state valid). Private helper methods and fields support both: they hide complexity (abstraction) and protect state (encapsulation).

Q3. How is polymorphism achieved in JavaScript, given it has no interfaces?

Through method overriding in class hierarchies (a subclass redefines a method), and through duck typing: any object with the expected methods can be used, whatever its class. TypeScript adds compile-time interface checks, but at runtime JavaScript simply calls the method if it exists. Guard optional capabilities with checks like typeof obj.method === "function".

Q4. How do OOP principles show up in a Playwright test framework?

Page objects and components encapsulate selectors and expose intent-based methods (abstraction, encapsulation); a shallow BasePage shares navigation and waits (inheritance); fixtures inject page and API clients into page objects (dependency inversion); and custom reporters or data providers are interchangeable objects with the same methods (polymorphism). The result is tests that read like specifications and change in one place when the UI changes.


Advertisement

❓ Frequently Asked Questions

🤔 Is JavaScript an object-oriented language?

Yes, but it is multi-paradigm. It supports OOP through objects, prototypes and classes, and also supports functional and procedural styles. Many projects mix them.

🤔 Do I need classes to use OOP in JavaScript?

No. Objects, closures and factory functions can provide encapsulation and polymorphism. Classes are a convenient, widely understood syntax for it.

🤔 What is the difference between OOP and functional programming?

OOP organises code around objects that hold state and behaviour. Functional programming organises code around pure functions and immutable data. Module 13 covers functional programming.

🤔 Which OOP question is asked most in QA interviews?

Explaining the four pillars with examples from a test framework (usually the Page Object Model), and the difference between overloading and overriding.


🏁 Summary

  • Encapsulation: keep state private and change it only through validated methods.
  • Abstraction: offer a small, intent-based public interface and hide the details.
  • Inheritance: reuse and extend shared behaviour with extends, keeping hierarchies shallow.
  • Polymorphism: call the same method on different objects; JavaScript supports it through overriding and duck typing.
  • Mixins, composition and SOLID principles keep object-oriented test frameworks flexible as they grow.

Next, continue with Lesson 43: Exception Handling. This completes Module 8. Module 9 covers errors and debugging, starting with exception handling.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in