Interview Q&A / Object-Oriented Programming

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How can polymorphism replace a long if-else or switch chain?

SHORT ANSWER

Give each case its own class with the same method, then call that method on the object. Adding a new case means adding a class, not editing the old, tested chain.

Explain it simply

A chain like "if type is bus, charge 10; else if type is metro, charge 15" must be edited every time a new transport appears, and that is where bugs creep in. If each transport knows its own fare, the caller simply asks "what is your fare?".

Example

js
class Bus   { fare(km) { return km * 2; } }
class Metro { fare(km) { return km * 3; } }
class Auto  { fare(km) { return 30 + km * 12; } }

function total(trip) {
  return trip.fare(10);          // no type checks
}

console.log(total(new Bus()));   // Output: 20
console.log(total(new Metro())); // Output: 30
console.log(total(new Auto()));  // Output: 150

Adding a Cab class needs no change in total. That is the Open/Closed Principle at work. A small, stable switch that never grows is fine; the smell is a chain that appears in many places.

What to say in the interview

"I replace type-checking conditionals by moving each branch into a class that implements a common method, then call it polymorphically. New behaviour is added by writing a new class, so existing code stays untouched."

Common mistakes

  • Turning a two-case, never-changing condition into a class hierarchy. That adds more code than it saves.

#polymorphism#refactoring#javascript

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.