Inheritance-tutorial
Inheritance is a core concept in object-oriented programming (OOP).
It allows a class (child/subclass) to acquire properties and methods from another class (parent/superclass).
This makes code reusable, organized, and easier to maintain.
In JavaScript (since ES6), inheritance is typically implemented using the class and extends keywords.
It allows a class (child/subclass) to acquire properties and methods from another class (parent/superclass).
This makes code reusable, organized, and easier to maintain.
In JavaScript (since ES6), inheritance is typically implemented using the class and extends keywords.
Example: Inheriting from Built-in Class (Date)
In this example, we create a custom class Moment that extends the built-in Date class to access its methods.
<!DOCTYPE html><html>
<body>
<script> class Moment extends Date { constructor(dateString) { super(dateString); // Call the parent class constructor } } var m = new Moment("August 15, 1947 20:22:10"); document.writeln("Year value:"); document.writeln(m.getFullYear()); </script>
</body>
</html>
Output
.webp)
Explanation
Example: Custom Class Inheritance
Here, we crate a base class Bike and extend it in the Vehicle class.
- extends allows Moment to inherit all methods from Date.
- super(dateString) calls the parent constructor with a date.
Example: Custom Class Inheritance
Here, we crate a base class Bike and extend it in the Vehicle class.
<!DOCTYPE html><html>
<body>
<script> class Bike { constructor() { this.company = "Honda"; } }
class Vehicle extends Bike { constructor(name, price) { super(); // Call parent constructor to set company this.name = name; this.price = price; } }
var v = new Vehicle("Shine", "40000"); document.writeln(v.company + " " + v.name + " " + v.price); </script>
</body>
</html>
Output
.webp)
Explanation
- Vehicle inherits company from Bike.
- super() inside the child constructor ensures the parent constructor runs.
Key Point
- extends keyword creates a subclass.
- super() calls the parent class constructor.
- Inheritance promotes code reuse and hierarchical relationships between classes.