Inheritance in Object OOP JavaScript
Inheritance in Object OOP JavaScript
Imagine your school system. You want to represent both Professors and Students in your
program. While they have different roles and responsibilities, they share some common
traits: they both have names and can introduce themselves.
Instead of creating separate classes for each, you can leverage inheritance. This allows
you to reuse code and build on existing classes. Let's see how:
class Person {
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(`My name is ${this.name}.`);
}
}
Use the extends keyword to tell them they inherit from Person.
gradePaper(paper) {
console.log(`Grading ${paper}...`);
}
introduceSelf() {
super.introduceSelf();
console.log(`...and I'm in year ${this.year}.`);
}
}
Benefits of Inheritance:
● Code reuse: Share common features like name and introduceSelf instead of
duplicating code.
● Reduced complexity: Organize your classes logically and avoid repeating yourself.
● Polymorphism: Different classes can implement the same method (e.g.,
introduceSelf) in their own unique way.
● Superclass: The "parent" class (e.g., Person) providing the base functionality.
● Subclass: The "child" class (e.g., Professor, Student) inheriting from the superclass
and adding specific details.
● extends: Keyword used to define a subclass based on a superclass.
● super(): Used in the subclass constructor to call the parent constructor and initialize
inherited properties.
● Override: When a subclass redefines a method already present in the superclass.
Example usage:
With inheritance, your code becomes cleaner, more organized, and easier to maintain, just
like a well-structured school system!