• in
InterCourses
CoursesBlogs
0
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking
○Declaring Variables○let and const in Practice○Operators○Type Conversion
○Conditionals○Switch Statement○For Loops○While Loop○Break and Continue
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions
○Arrays○Array Mutation Methods○Array Search and Slice○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every
○Objects○Object Methods and Destructuring○JSON○Math and Date○Date Basics
○02 Template Literals○String Methods○Regular Expressions
○Higher-Order Functions○Callbacks○map, filter, and reduce○Recursion○Project - Data Transform Pipeline
○OOP Introduction○Classes●Inheritance○Encapsulation
○Asynchronous JavaScript○Promises and Async Await○Async API Simulation

Inheritance

Inheritance lets a child class reuse and extend the behavior of a parent class.

Basic inheritance

javascript
class Animal {
    constructor(name) {
        this.name = name;
    }

    speak() {
        return `${this.name} makes a sound.`;
    }

    toString() {
        return `Animal(${this.name})`;
    }
}

class Dog extends Animal {
    speak() {
        return `${this.name} barks.`;
    }
}

class Cat extends Animal {
    speak() {
        return `${this.name} meows.`;
    }
}

const dog = new Dog("Rex");
dog.speak();     // "Rex barks."
dog.toString();  // "Animal(Rex)" — inherited from Animal

Calling the parent with super

javascript
class Employee extends Person {
    constructor(name, age, company) {
        super(name, age);        // calls Person's constructor
        this.company = company;
    }

    introduce() {
        return `${super.introduce()} I work at ${this.company}.`;
    }
}

instanceof check

javascript
dog instanceof Dog;     // true
dog instanceof Animal;  // true — Dog IS an Animal
dog instanceof Cat;     // false

Your Task

  1. Create a base class Shape with:
    • Constructor (color = "black").
    • area() — returns 0 (to be overridden).
    • toString() — returns "Shape(color: black)".
  2. Create Circle extends Shape with:
    • Constructor (radius, color) — calls super(color).
    • area() — returns Math.PI * radius² rounded to 2 decimal places.
    • toString() — returns "Circle(radius: 5, color: red, area: 78.54)".
  3. Create Rectangle extends Shape with:
    • Constructor (width, height, color).
    • area() — returns width * height.
    • toString() — returns "Rectangle(4×6, color: blue, area: 24)".
  4. Display in #output: both toString() values joined with " | ".
Hint 1
1 / 3
HINT 1

Use extends to inherit: class Child extends Parent {}

Loading editor…
READY
intercourses
javascript