Find a course

Module 3: Inheritance and PolymorphismLesson 7 of 1214 min

Polymorphism: One Call, Many Behaviors

Use polymorphism and dynamic dispatch to replace long if-else chains, and see how duck typing lets unrelated objects share an interface without inheritance.

Step 1 of 14Learn

The switch statement that kept growing

A drawing app computes areas with one big function:

function area(shape) {
  if (shape.type === 'circle') return Math.PI * shape.r ** 2;
  if (shape.type === 'rect') return shape.w * shape.h;
  if (shape.type === 'triangle') return 0.5 * shape.base * shape.height;
}

There are similar functions for perimeter, draw, toSvg and hitTest. Each time the team adds a shape, they edit five functions, and the bug reports always come from the one they missed.

Polymorphism ("many forms") flips the design. Each shape becomes a class that knows how to compute its own area:

class Circle { constructor(r) { this.r = r; }
  area() { return Math.PI * this.r ** 2; } }
class Rect { constructor(w, h) { this.w = w; this.h = h; }
  area() { return this.w * this.h; } }
class Triangle { constructor(b, h) { this.b = b; this.h = h; }
  area() { return 0.5 * this.b * this.h; } }

const shapes = [new Circle(1), new Rect(2, 3), new Triangle(4, 5)];
const total = shapes.reduce((sum, s) => sum + s.area(), 0);

The loop calls s.area() without knowing or caring what kind of shape s is. Each object answers in its own way. Adding a hexagon now means writing one new class with an area() method; the loop, and every other function that works with shapes, stays untouched.

Step 2 of 14Practice · Work it out

In the example above, what is total (the sum of the three areas)? Use π ≈ 3.14159 and round to two decimal places.

Step 3 of 14Practice · Chart

What each shape's area() returns

Which object's area() returns the largest value?

Tap the bar that answers the question, then press Check.

What each shape's area() returnsBar chart with 3 categories: Circle(1): 3.14; Rect(2, 3): 6; Triangle(4, 5): 10.0246810Circle(1)Rect(2, 3)Triangle(4, 5)3.14610
One loop, three different area() methods chosen by the objects themselves.
What each shape's area() returns
ItemArea
Circle(1)3.14
Rect(2, 3)6
Triangle(4, 5)10

Step 4 of 14Learn

Dynamic dispatch: how the right method gets picked

When code calls s.area(), the language decides at run time which area to run, based on the actual object s refers to. This is called dynamic dispatch (or late binding).

In JavaScript, every object has a hidden link to its class's prototype, where methods live. Calling s.area() looks for area on the object, then on its prototype, then up the inheritance chain until it finds one. If s is a Circle, the search finds Circle.prototype.area; if it's a Rect, it finds Rect.prototype.area.

Inheritance and overriding plug into the same mechanism:

class Employee {
  pay() { return this.salary / 12; }
  payslip() { return this.name + ': ' + this.pay().toFixed(2); }
}
class Contractor extends Employee {
  pay() { return this.hours * this.rate; }   // override
}

payslip() is written once in Employee, yet when it runs on a contractor, its call to this.pay() dispatches to Contractor.pay. The parent's method calls the child's version without knowing the child exists. That's what makes frameworks possible: a framework class calls this.render(), and your subclass decides what rendering means.

Statically typed languages such as Java and C# add a compile-time check: a variable declared as Employee can hold any subclass, and the compiler verifies that pay() exists on Employee, while the actual method is still chosen at run time.

Step 5 of 14Practice · What would you do?

What would you do?

Given the Employee and Contractor classes above, consider:

const c = new Contractor();
c.name = 'Ola'; c.hours = 10; c.rate = 50; c.salary = 120000;
console.log(c.payslip());

What is printed?

Step 6 of 14Practice · Diagram

Dynamic dispatch: finding s.area() at run time

For a Circle, where does the lookup find area()?

Tap the shape that answers the question, then press Check.

Dynamic dispatch: finding s.area() at run timeProcess diagram: The object itself → Its class prototype → Parent prototypes → Not found: TypeError.The objectitselfIts classprototypeParentprototypesNot found:TypeError
The object itself

Own fields such as r. Methods usually are not stored here.

Its class prototype

Circle.prototype.area is found here for a Circle.

Parent prototypes

Searched next, up the inheritance chain.

Not found: TypeError

"area is not a function".

Step 7 of 14Learn

Duck typing: no inheritance required

"If it walks like a duck and quacks like a duck, it's a duck." In dynamically typed languages such as JavaScript and Python, polymorphism doesn't need a shared parent class at all. Any object with the right method works:

const exporters = [
  { export(data) { return JSON.stringify(data); } },
  { export(data) { return data.map(r => r.join(',')).join('
'); } },
];
exporters.forEach(e => save(e.export(rows)));

The two objects have nothing in common except a method called export with the same meaning. That shared expectation, "has an export(data) method that returns a string", is an interface in the informal sense. Duck typing means relying on what an object can do rather than what class it belongs to.

Python uses this everywhere. A for loop works on lists, files, dictionaries and your own classes, as long as they provide the iteration methods. len(x) works on anything with a __len__ method.

The trade-off is safety. If an object lacks the method, you find out only when the code runs and crashes with "export is not a function". Statically typed languages make interfaces explicit so the compiler catches that earlier, and TypeScript adds the same checks on top of JavaScript. You'll see formal interfaces in the next lesson.

Step 8 of 14Practice · Match the pairs

Match each term to its meaning.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Polymorphism
  2. Dynamic dispatch
  3. Overriding
  4. Duck typing

Step 9 of 14Practice · Code challenge

Write two classes, Circle (constructor takes r) and Square (constructor takes side), each with an area() method. Then write a function totalArea(shapes) that returns the sum of area() for every shape in the array, without checking what type each shape is.

Runs in a sandbox in your browser.
  • totalArea([new Square(2), new Square(3)])
  • Math.round(totalArea([new Circle(1)]) * 1000) / 1000
  • Math.round(totalArea([new Circle(2), new Square(1)]) * 100) / 100
  • totalArea([])

Step 10 of 14Learn

Polymorphism beyond classes

Polymorphism shows up in more forms than overridden methods.

  • Subtype polymorphism is what you've just seen: a call on a parent type runs the subclass's version.
  • Parametric polymorphism, better known as generics, lets one piece of code work with many types. A TypeScript Array<T>, a Java List<String> or a C# Dictionary<string, int> is written once and works for any element type.
  • Ad hoc polymorphism, or overloading, gives one name several versions that take different parameter types. In Java, print(int) and print(String) can be separate methods; the compiler picks one based on the arguments. JavaScript and Python don't support classic overloading, so one function checks its arguments instead, or you use default parameters.

Operator overloading is a special case: Python lets a class define __add__ so that money_a + money_b calls your method, and C# and C++ offer similar features. JavaScript doesn't, which is why value objects there use methods like a.add(b).

In everyday OOP conversation, "polymorphism" almost always means the first kind: many classes, one interface, behavior chosen by the object at run time.

Step 11 of 14Practice · Match the pairs

Match each form of polymorphism to an example.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Subtype polymorphism
  2. Generics
  3. Overloading
  4. Operator overloading

Step 12 of 14Diagram

Forms of polymorphism

Forms of polymorphismHierarchy diagram: Polymorphism, Subtype, Parametric (generics), Ad hoc (overloading), Operator overloading.PolymorphismSubtypeParametric(generics)Ad hoc (overloading)Operatoroverloading

Tap a shape with to see more.

Polymorphism
Subtype

Overridden methods chosen at run time. What "polymorphism" usually means.

Parametric (generics)

Array<T>, List<String>: one code, many types.

Ad hoc (overloading)

Same name, different parameter types; not in JS or Python.

Operator overloading

Python __add__ makes a + b call your method.

Step 13 of 14Note

Step 14 of 14Practice · True or false

In JavaScript, two classes must share a common superclass before a function can call the same method on instances of both.