Inheritance: Building on Existing Classes in JavaScript (Simplified)
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:
Step 1: Define the "Person" base class:
Think of it as the common ground for both professors and students.
class Person {
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(`My name is ${this.name}.`);
}
}
Step 2: Derive "Professor" and "Student" from "Person":
Use the extends keyword to tell them they inherit from Person.
class Professor extends Person {
constructor(name, teaches) {
super(name); // Call parent constructor
this.teaches = teaches;
}
gradePaper(paper) {
console.log(`Grading ${paper}...`);
}
// Override introduceSelf to add professor details
introduceSelf() {
super.introduceSelf(); // Call parent introduceSelf
console.log(`...and I teach ${this.teaches}.`);
}
}
class Student extends Person {
constructor(name, year) {
super(name);
this.year = year;
}
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.
Key points to remember:
● 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:
const walsh = new Professor("Walsh", "Psychology");
walsh.introduceSelf(); // "My name is Walsh. ...and I teach
Psychology."
const summers = new Student("Summers", 1);
summers.introduceSelf(); // "My name is Summers. ...and I'm in year
1."
const pratt = new Person("Pratt");
pratt.introduceSelf(); // "My name is Pratt."
With inheritance, your code becomes cleaner, more organized, and easier to maintain, just
like a well-structured school system!