Inheritance & Polymorphism
Classes & Object-Oriented Programming · Coding Fundamentals track
8 min read
In this module
Building on Existing Classes
You've got a working Shape class with handy methods. Now you need a Circle that does everything a Shape does, plus has a radius and a circle-specific area formula. You could copy Shape's code into Circle, but then you'd have the same logic in two places, drifting apart over time.
Inheritance solves this. A new class (the child or subclass) can extend an existing class (the parent or superclass), automatically picking up all its fields and methods. The child can then add new fields and methods, or override existing methods with its own version.
class Animal { name age
constructor(name, age) { this.name = name this.age = age }
function speak() { print(this.name + " makes a sound") }}
class Dog extends Animal { breed
constructor(name, age, breed) { super(name, age) // call the parent's constructor this.breed = breed }
function speak() { // override the parent's method print(this.name + " barks!") }
function fetch() { // new method only Dogs have print(this.name + " fetches the ball") }}A Dog is an Animal. It has everything an Animal has (name, age, speak) plus its own additions (breed, fetch). The speak method gets overridden — call it on a Dog and you get a bark, not a generic sound.
Inheritance lets a child class automatically acquire the fields and methods of a parent class. The child can add new capabilities and override existing methods. This creates an "is-a" relationship: a Dog is an Animal.
Polymorphism: Many Forms
Polymorphism literally means "many forms." It lets you write code against a general type and have it automatically pick the right specific behaviour.
animals = [ new Dog("Rex", 3, "Lab"), new Cat("Whiskers", 5), new Bird("Tweety", 2)]
for animal in animals { animal.speak()}// Output:// Rex barks!// Whiskers meows!// Tweety chirps!The loop calls speak() on each animal. The variable type is Animal, but the method that actually runs depends on the object's real type. This is dynamic dispatch: the correct method is selected at runtime, based on the object's actual class.
Here's the hierarchy behind that loop. The solid arrows mean "extends". Each child lists speak() again because it overrides the parent's version, and Dog adds fetch() of its own:
When the loop runs animal.speak(), the compiler only knows it has an Animal. The decision about which box's speak() to call is put off until the program is running and can look at the actual object. The last lesson in this module shows the table that makes that lookup fast.
The Is-A Test
Inheritance creates a type hierarchy. A Dog is an Animal. A Circle is a Shape. So anywhere you need an Animal, a Dog will do. Anywhere you need a Shape, a Circle works.
That substitutability is the Liskov Substitution Principle: a child class should be usable anywhere the parent is expected, without breaking the program's correctness.
function print_area(shape) { // accepts any Shape print("Area: " + shape.area())}
print_area(new Circle(5)) // works with Circleprint_area(new Rectangle(3, 4)) // works with Rectangleprint_area(new Triangle(3, 4, 5)) // works with TriangleThe function doesn't need to know the specific shape type. It just calls area(), and polymorphism makes sure the right calculation runs.
Method Overriding
When a child class defines a method with the same name as a parent's, the child's version overrides the parent's. The child can still reach back to the parent's version through super.
class Employee { function calculate_pay() { return this.hours * this.rate }}
class Manager extends Employee { function calculate_pay() { base = super.calculate_pay() // call parent's version return base + this.bonus // add manager-specific bonus }}That pattern — call the parent's implementation, then extend it — is everywhere. It lets you reuse base behaviour while bolting on specialisation.
Whether an override actually wins depends on the language. In C++, a method only dispatches on the object's real type if it's marked virtual. Predict the three lines this prints before running it, then delete virtual from Animal::speak and predict again.
Show the answer
With virtual, the pointer and the reference both reach the real Dog, so you get "Rex barks!" twice. Without it, C++ picks the method from the declared type, Animal, and both say "Rex makes a sound" (you'll also need to delete override, which only compiles on a virtual method). The copy says "makes a sound" in both versions: assigning a Dog to a plain Animal variable copies just the Animal fields into a new Animal object. That's called slicing, and it's why polymorphism in C++ goes through pointers and references.
Composition vs. Inheritance
Inheritance is powerful, but it isn't always the right tool. Composition — having an object hold other objects — is often a better fit.
// Inheritance: Car IS-A Engine? That's wrong.class Car extends Engine { ... } // bad design
// Composition: Car HAS-AN Engine. That's right.class Car { engine = new Engine() transmission = new Transmission()
function start() { this.engine.ignite() this.transmission.engage() }}Rule of thumb: use inheritance for genuine "is-a" relationships (a Dog is an Animal). Use composition for "has-a" relationships (a Car has an Engine). Modern practice strongly favours composition over deep inheritance hierarchies, because it ends up more flexible and less coupled.
Abstract Classes
An abstract class can't be instantiated directly. It only ever serves as a base for other classes. It can define some methods fully and leave others abstract (undefined), forcing child classes to fill in the missing pieces.
abstract class Shape { color
function get_color() { // concrete method return this.color }
abstract function area() // must be implemented by children abstract function perimeter() // must be implemented by children}You can't write new Shape() — it's incomplete. But new Circle() or new Rectangle() that extends Shape and provides the missing methods is fine. Abstract classes sit between interfaces (pure contracts) and concrete classes (fully implemented), inheriting properties of both.