Menu
Coddy logo textTech

Inheriting Properties&Methods

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

When a class extends another class, it inherits all the properties and methods from the parent class. This means child classes automatically have access to everything defined in the parent class.

Let's create a parent class with properties and methods:

class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  eat() {
    return `${this.name} is eating`;
  }
  
  sleep() {
    return `${this.name} is sleeping`;
  }
}

Now, let's create a child class that inherits from Animal:

class Dog extends Animal {
  constructor(name, age, breed) {
    super(name, age);
    this.breed = breed;
  }
}

Create an instance of the Dog class:

const rex = new Dog("Rex", 3, "German Shepherd");

Now, even though we didn't define eat() and sleep() in the Dog class, we can still use these methods:

console.log(rex.eat());  // Outputs: Rex is eating
console.log(rex.sleep()); // Outputs: Rex is sleeping

And we can access all inherited properties:

console.log(rex.name);  // Outputs: Rex
console.log(rex.age);   // Outputs: 3
console.log(rex.breed); // Outputs: German Shepherd
challenge icon

Challenge

Create a Cake class that extends Dessert and export it. The Cake should have:

  • All inherited properties and methods from Dessert
  • A new property flavor
  • A new method addCandles() that returns a string “Added candles to ${this.name}!”

Cheat sheet

Child classes inherit all properties and methods from their parent class using the extends keyword:

class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  eat() {
    return `${this.name} is eating`;
  }
  
  sleep() {
    return `${this.name} is sleeping`;
  }
}

class Dog extends Animal {
  constructor(name, age, breed) {
    super(name, age);
    this.breed = breed;
  }
}

const rex = new Dog("Rex", 3, "German Shepherd");
console.log(rex.eat());  // Rex is eating
console.log(rex.name);   // Rex
console.log(rex.breed);  // German Shepherd

The child class can access all inherited properties and methods without redefining them.

Try it yourself

import { Dessert } from './desserts.js';
import { Cake } from './desserts.js';

// Test code - don't modify
const myCake = new Cake("Birthday Cake", 300, "Chocolate");
console.log(myCake.describe());   // Should output "Birthday Cake has 300 calories"
console.log(myCake.flavor);       // Should output "Chocolate"
console.log(myCake.addCandles()); // Should output "Added candles to Birthday Cake!"
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