Class inheritance is a core concept in object-oriented programming (OOP) that allows one class (the subclass) to inherit properties and methods from another class (the superclass). JavaScript, with the introduction of class
syntax in ECMAScript 6 (ES6), makes inheritance more straightforward and readable.
What is Class Inheritance?
In JavaScript, class inheritance enables one class to acquire the behavior (methods) and attributes (properties) of another. This promotes code reuse and allows developers to define hierarchical relationships between objects.
Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog("Rex");
dog.speak(); // Output: Rex barks.
Here, Dog
inherits the speak
method from Animal
but overrides it with its own implementation.
Syntax of Class Inheritance
The extends
keyword is used to create a subclass, and the super
keyword is used to call the parent class’s constructor or methods.
Basic Syntax:
class ParentClass {
constructor(args) {
// Initialization logic
}
method1() {
// Method logic
}
}
class ChildClass extends ParentClass {
constructor(args) {
super(args); // Call ParentClass's constructor
// Additional initialization
}
method2() {
// Subclass-specific logic
}
}
Key Concepts in JavaScript Class Inheritance
1. The extends
Keyword
Indicates that a class inherits from another class.
class Vehicle {
constructor(type) {
this.type = type;
}
}
class Car extends Vehicle {
constructor(type, brand) {
super(type);
this.brand = brand;
}
}
const myCar = new Car("Car", "Toyota");
console.log(myCar.type); // Output: Car
console.log(myCar.brand); // Output: Toyota
2. The super
Keyword
- Used to call the constructor of the parent class.
- Also used to invoke parent methods.
class Parent {
greet() {
return "Hello from Parent";
}
}
class Child extends Parent {
greet() {
return `${super.greet()} and Child`;
}
}
const child = new Child();
console.log(child.greet()); // Output: Hello from Parent and Child
3. Overriding Methods
A subclass can override methods of the parent class to implement specialized behavior.
Benefits of Class Inheritance
- Code Reusability: Inherit common functionality from a base class, avoiding duplication.
- Modularity: Break down functionality into base and specialized classes.
- Scalability: Extend existing classes to introduce new features without modifying the original code.
Real-World Use Case: Class Hierarchies
Inheritance is often used to model real-world hierarchies. For example:
class Employee {
constructor(name, position) {
this.name = name;
this.position = position;
}
work() {
console.log(`${this.name} is working.`);
}
}
class Manager extends Employee {
work() {
super.work();
console.log(`${this.name} is managing the team.`);
}
}
const manager = new Manager("Alice", "Manager");
manager.work();
// Output:
// Alice is working.
// Alice is managing the team.
Common Mistakes in Class Inheritance
- Forgetting to Call
super()
in Subclass Constructor:- The
super()
function must be called before accessingthis
in the subclass.
- The
- Misusing Static Members:
- Static methods belong to the class itself, not its instances. Don’t expect static methods to be inherited.
- Overcomplicating Inheritance Chains:
- Deep inheritance hierarchies can lead to complex and hard-to-maintain code.
Advanced Features of Class Inheritance
1. Abstract Classes
JavaScript doesn’t have built-in abstract classes, but you can simulate them by throwing an error if a method is not implemented.
class Shape {
constructor() {
if (this.constructor === Shape) {
throw new Error("Abstract class cannot be instantiated");
}
}
calculateArea() {
throw new Error("Method 'calculateArea()' must be implemented");
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
calculateArea() {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle(5);
console.log(circle.calculateArea()); // Output: 78.53981633974483
2. Inheritance from Built-in Objects
You can extend built-in objects like Array
or Error
.
class CustomArray extends Array {
customMethod() {
console.log("Custom logic here.");
}
}
const myArray = new CustomArray(1, 2, 3);
myArray.customMethod(); // Output: Custom logic here.
Conclusion
JavaScript class inheritance is a powerful tool for building scalable, reusable, and organized code. By understanding how to use extends
, super
, and method overriding, you can leverage the full potential of object-oriented programming in JavaScript. For detailed tutorials and more examples, visit The Coding College.