OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 30

Class Inheritance (extends and super)

By Ratan Updated: 16 Oct 2026

Inherit properties and methods from parent classes using extends and super() constructor calls.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Extend behavior while honoring the base contract

extends links a derived class to a base class. A derived constructor calls super before using this, so the base instance state is initialized. A method can override an inherited method and call the base implementation through super.method().

class Lesson {
  constructor(title) { this.title = title; }
  describe() { return 'Lesson: ' + this.title; }
}
class TimedLesson extends Lesson {
  constructor(title, minutes) {
    super(title);
    if (!Number.isFinite(minutes) || minutes <= 0) {
      throw new RangeError('Duration must be positive');
    }
    this.minutes = minutes;
  }
  describe() {
    return super.describe() + ' (' + this.minutes + ' min)';
  }
}
const lesson = new TimedLesson('Closures', 20);
console.log(lesson.describe()); // Lesson: Closures (20 min)
console.log(lesson instanceof Lesson); // true

Initialization order

The base constructor handles base initialization. The derived constructor adds its own rules afterward. Accessing this before super in a derived constructor is an error. If you omit a derived constructor, JavaScript provides default forwarding behavior suitable for the ordinary case.

Private fields are not protected fields

A base class's #private fields cannot be directly named by derived-class code. Expose a deliberate method or getter when a subclass needs a supported operation. Do not assume inheritance grants access to all implementation details.

Use inheritance selectively

TimedLesson is still a Lesson with extra timing information. A Course containing many lessons is usually a composition relationship, not “Course extends Array” merely to reuse list methods. Keep subclasses substitutable: an override should not silently break assumptions made by callers of the base interface.

Practice

  1. Add VideoLesson with a URL field and an overridden description.
  2. Pass several lesson types to a function that calls describe.
  3. Test zero, negative and NaN durations.
  4. Explain why calling super.describe preserves the base message while adding detail.

हिन्दी संकेत: inheritance का अर्थ valid base behavior को आगे बढ़ाना है; केवल code reuse के लिए हर relationship को extends न बनाएं।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat