Skip to main content

JavaScript Classes

JavaScript Method Overriding

Written by Published

A child class can replace a method it inherited with its own version.

Define a method with the same name and the child's version wins.

This is what lets different classes respond to the same call in their own way.

Example

Example

javascript

class Animal {
  speak() {
    return "some sound";
  }
}

class Dog extends Animal {
  speak() {
    return "woof";
  }
}

console.log(new Dog().speak());

The output is woof; the parent's version was replaced.

What is Overriding?

The child's method is found first, so it is the one that runs.

The parent's version is still reachable through super.

Different classes offering the same method is called polymorphism.

Syntax

Syntax

javascript

class Child extends Parent {
  method() {
    // replaces the parent's method
  }
}

Same name, same idea, different behaviour.

Polymorphism in Practice

One loop can call the same method on very different objects.

Each one answers in its own way.

Example

Example

javascript

class Animal {
  speak() {
    return "some sound";
  }
}

class Dog extends Animal {
  speak() {
    return "woof";
  }
}

class Cat extends Animal {
  speak() {
    return "meow";
  }
}

const sounds = [new Dog(), new Cat(), new Animal()].map(function (a) {
  return a.speak();
});

console.log(sounds.join(" "));

The output is woof meow some sound.

Keeping the Parent's Work

super lets you add to the inherited version.

Example

Example

javascript

class Animal {
  describe() {
    return "an animal";
  }
}

class Dog extends Animal {
  describe() {
    return super.describe() + ", specifically a dog";
  }
}

console.log(new Dog().describe());

Nothing was duplicated.

The Method Is Chosen at Runtime

JavaScript looks at the actual object, not the variable's name.

That is why the same code gives different results.

Example

Example

javascript

class Animal {
  speak() {
    return "generic";
  }
}

class Dog extends Animal {
  speak() {
    return "woof";
  }
}

function makeItSpeak(animal) {
  return animal.speak();
}

console.log(makeItSpeak(new Dog()));
console.log(makeItSpeak(new Animal()));

One function, two different answers.

Overriding a Constructor

The same idea applies, but super() is compulsory.

Example

Example

javascript

class Shape {
  constructor(sides) {
    this.sides = sides;
  }
}

class Square extends Shape {
  constructor() {
    super(4);
    this.name = "square";
  }
}

const square = new Square();

console.log(square.name + " has " + square.sides + " sides");

The child fixed the value the parent needed.

Keep the Same Shape

An override should accept the same arguments and return the same kind of value.

Changing that makes the classes no longer interchangeable.

Example

Example

javascript

class Formatter {
  format(text) {
    return text;
  }
}

class LoudFormatter extends Formatter {
  format(text) {
    return text.toUpperCase();
  }
}

console.log(new LoudFormatter().format("hello"));

Both take a string and return a string, so either can be used.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Method Overriding</title>
</head>
<body>

  <h1>Method Overriding</h1>

  <p id="out"></p>

  <script>
    class Shape {
      area() {
        return 0;
      }
      describe() {
        return this.constructor.name + " has area " + this.area();
      }
    }

    class Square extends Shape {
      constructor(side) {
        super();
        this.side = side;
      }
      area() {
        return this.side * this.side;
      }
    }

    class Circle extends Shape {
      constructor(radius) {
        super();
        this.radius = radius;
      }
      area() {
        return Math.round(Math.PI * this.radius * this.radius);
      }
    }

    const shapes = [new Square(4), new Circle(3)];

    document.getElementById("out").innerHTML = shapes.map(function (s) {
      return s.describe();
    }).join("<br>");
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try another shape:

Add a Rectangle class with its own area and put it in the list.

Important Points

  • A child method with the same name replaces the parent's.
  • super.method() still reaches the original.
  • Different classes answering the same call is polymorphism.
  • The method is chosen from the actual object at runtime.
  • Keep the arguments and return type the same.

Conclusion

Overriding is what makes inheritance useful rather than just tidy.

Polymorphism lets one piece of code work with many types.

Keeping the shape consistent is what keeps that possible.