Menu
Coddy logo textTech

Inheritance

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

Inheritance in JavaScript OOP is a way for one class to gain access to all the properties and methods from another class.

Let's look at an example. Create a parent class:

class Vehicle {
 constructor(brand, model) {
   this.brand = brand;
   this.model = model;
 }
 drive() {
   console.log("Driving!");
 }
}

Now create a child class that inherits from Vehicle:

// Car inherits from Vehicle
class Car extends Vehicle {
 honk() {
   console.log("Beep beep!");
 }
}

Create an instance of the child class:

const myCar = new Car("Toyota", "Camry");

Access properties and methods:

console.log(myCar.brand);  // "Toyota" - inherited from Vehicle
console.log(myCar.model);  // "Camry" - inherited from Vehicle
// Car can access Vehicle's methods
myCar.drive();  // "Driving!" - inherited from Vehicle
// Car also has its own methods
myCar.honk();   // "Beep beep!" - specific to Car
challenge icon

Challenge

You're given an Animal class and a Dog class that inherits from it. Your task is to create a myDog object with name "Buddy" and age 3.

Cheat sheet

Inheritance allows one class to gain access to properties and methods from another class using the extends keyword.

Parent class:

class Vehicle {
 constructor(brand, model) {
   this.brand = brand;
   this.model = model;
 }
 drive() {
   console.log("Driving!");
 }
}

Child class inheriting from parent:

class Car extends Vehicle {
 honk() {
   console.log("Beep beep!");
 }
}

The child class inherits all properties and methods from the parent class and can also have its own:

const myCar = new Car("Toyota", "Camry");
console.log(myCar.brand);  // "Toyota" - inherited
myCar.drive();  // "Driving!" - inherited
myCar.honk();   // "Beep beep!" - own method

Try it yourself

import { Dog } from './animal.js';

// TODO: Create myDog object with name "Buddy" and age 3.


// Test code - don't modify
console.log(myDog.name);  // Should output "Buddy"
console.log(myDog.age);  // Should output 3
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