Menu
Coddy logo textTech

Overriding Inherited Methods

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 36 of 56.

Method overriding is when a child class provides its own implementation of a method that it inherited from a parent class. The child's version "overrides" (replaces) the parent's version.

Simple Example:

Create a parent class with a method:

class Vehicle {
  start() {
    return "Vehicle starting...";
  }
}

Create a child class that extends the parent:

class Car extends Vehicle {
  // This OVERRIDES Vehicle's start() method
  start() {
    return "Car engine roaring to life!";
  }
}

Use the classes:

const vehicle = new Vehicle();
const car = new Car();

console.log(vehicle.start());      // "Vehicle starting..." (original)
console.log(car.start());          // "Car engine roaring to life!" (overridden)

Key Rules for Overriding:

  1. Same method name as parent
  1. Same or compatible parameters
  1. Child's version is called on child objects
  1. No special keywords needed - just define the method
challenge icon

Challenge

You're given a Shape parent class and a Circle child class. The parent class has a calculateArea() method that returns 0.

Your task is to override the calculateArea() method in the Circle class to calculate the actual area of a circle.

The formula for circle area is: π × radius²
In JavaScript: Math.PI * this.radius * this.radius

Cheat sheet

Method overriding occurs when a child class provides its own implementation of a method inherited from a parent class. The child's version replaces the parent's version.

Example:

class Vehicle {
  start() {
    return "Vehicle starting...";
  }
}

class Car extends Vehicle {
  // Overrides Vehicle's start() method
  start() {
    return "Car engine roaring to life!";
  }
}

const vehicle = new Vehicle();
const car = new Car();

console.log(vehicle.start());  // "Vehicle starting..."
console.log(car.start());      // "Car engine roaring to life!"

Key Rules:

  • Use the same method name as the parent
  • Use same or compatible parameters
  • The child's version is called on child objects
  • No special keywords needed - just define the method in the child class

Try it yourself

import { Shape } from './shapes.js';
import { Circle } from './shapes.js';

// Test your implementation
const myCircle = new Circle(5);
console.log(myCircle.calculateArea());
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming