Inheritance
Inheritance allows one object or class to use the properties and methods of another.
It helps avoid code duplication and creates a clear relationship between related objects.
What Is Inheritance?
Inheritance means:
- One class is based on another class
- The child class reuses the parent’s behavior
- New features can be added without rewriting code
This is a core concept in Object-Oriented Programming.
Why Inheritance Is Useful
- Reduces repeated code
- Makes code easier to maintain
- Represents real-world relationships
Inheritance helps applications scale cleanly.
Inheritance with Classes
JavaScript uses the extends keyword
to create inheritance between classes.
class Person {
constructor(name) {
this.name = name;
}
greet() {
return "Hello, " + this.name;
}
}
This is the parent (base) class.
Creating a Child Class
A child class inherits from a parent class
using extends.
class Employee extends Person {
constructor(name, role) {
super(name);
this.role = role;
}
getRole() {
return this.role;
}
}
The super() call invokes the parent constructor.
Using the Inherited Class
let emp = new Employee("Alex", "Developer");
console.log(emp.greet());
console.log(emp.getRole());
The child class can access both its own methods and inherited methods.
Overriding Methods
A child class can override a parent method to provide specialized behavior.
class Employee extends Person {
greet() {
return "Welcome, " + this.name;
}
}
JavaScript uses the child’s method instead of the parent’s.
Inheritance Behind the Scenes
Even with classes, JavaScript still uses the prototype chain.
Inheritance connects the child’s prototype to the parent’s prototype.
This is why inherited methods work.
Real-World Example
Think of inheritance like job roles:
- All employees share common traits
- Each role adds specific responsibilities
Inheritance models this naturally.
Common Beginner Mistakes
- Forgetting to call
super() - Using inheritance when composition fits better
- Creating deep inheritance chains
Keep inheritance simple and meaningful.
Thumb Rules
- Use inheritance for “is-a” relationships
- Call
super()in child constructors - Avoid unnecessary inheritance
- Prefer clarity over cleverness
What Comes Next?
Now that you understand inheritance, the next concept is controlling function behavior using closures.
In the next lesson, we will learn about closures.