Inheritance lets one class get features from another class. It helps reuse code and organize related things together.
0
0
Inheritance using classes in Javascript
Introduction
When you want a new object to have all features of an existing object plus some new ones.
When you want to group similar objects but with small differences.
When you want to avoid repeating the same code in many places.
When you want to create a clear relationship between general and specific things.
When you want to extend or customize behavior of existing classes.
Syntax
Javascript
class ParentClass { // parent class code } class ChildClass extends ParentClass { // child class code }
extends keyword is used to inherit from the parent class.
The child class gets all methods and properties of the parent class automatically.
Examples
Dog inherits from Animal. Dog can use speak() and also has bark().
Javascript
class Animal { speak() { console.log('Animal speaks'); } } class Dog extends Animal { bark() { console.log('Dog barks'); } }
Car inherits Vehicle but replaces start() with its own version.
Javascript
class Vehicle { start() { console.log('Vehicle started'); } } class Car extends Vehicle { start() { console.log('Car started'); } }
Sample Program
Student inherits from Person. It uses super to call the parent constructor. Student has all Person features plus study().
Javascript
class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello, my name is ${this.name}`); } } class Student extends Person { constructor(name, grade) { super(name); this.grade = grade; } study() { console.log(`${this.name} is studying in grade ${this.grade}`); } } const student1 = new Student('Alice', 5); student1.greet(); student1.study();
OutputSuccess
Important Notes
Use super() in the child constructor to call the parent constructor.
Child classes can add new methods or override existing ones from the parent.
Inheritance helps keep code clean and easy to manage.
Summary
Inheritance lets a class get features from another class using extends.
Child classes can add or change behavior from the parent class.
Use super() to call the parent constructor inside the child.