Introduction
Inheritance is a core concept in Object-Oriented Programming (OOP) that allows one class to acquire the properties and behaviors of another class. It helps improve code reusability, organization, and maintenance.
In simple terms, inheritance means creating a new class from an existing class to reuse and extend its features.
What is Inheritance
Inheritance allows a child class (subclass) to use properties and methods from a parent class (superclass). The child class can also add new features or modify existing ones.
Why Inheritance is Important
Code Reusability helps avoid writing the same code again
Better Organization makes code structured and easy to understand
Easy Maintenance allows changes in one place to reflect in others
Real World Modeling helps represent real-life relationships in programming
Types of Inheritance
Single Inheritance where one child class inherits one parent class
Multilevel Inheritance where a class is derived from another derived class
Hierarchical Inheritance where multiple child classes inherit one parent class
Multiple Inheritance conceptually where supported through interfaces
Example of Inheritance in JavaScript
class Animal {
eat() {
console.log("This animal eats food");
}
}
class Dog extends Animal {
bark() {
console.log("Dog is barking");
}
}
let d = new Dog();
d.eat();
d.bark();
Real World Example
A Vehicle class can be a parent class
Car, Bike, and Truck can be child classes
All vehicles share common properties like speed and fuel
Each vehicle also has unique features
Advantages of Inheritance
Reduces code duplication
Improves code scalability
Makes software easier to maintain
Encourages clean and logical design
Conclusion
Inheritance is an important OOP concept that allows code reuse, better structure, and efficient software development. It is widely used in modern programming languages.