Inheritance With Super
Introduction: Building On What Already Exists
In our last lesson, we learned how to build a secure Account class using private fields and accessors. This is a great foundation, but in the real world, software often requires many different types of accounts. You might need a SavingsAccount that earns interest, a CheckingAccount with transaction fees, or a BusinessAccount with higher limits. If we were to write a completely new class for each of these, we would end up repeating the same code for the owner's name and the balance logic over and over again.
In this lesson, we will explore inheritance. Inheritance allows us to create a new class based on an existing one. We can take all the features of our original Account class and "specialize" them for a SavingsAccount. This helps us avoid duplication and makes our code much easier to maintain. By the end of this lesson, you will know how to link classes together so that they share behavior while still maintaining their own unique features.
Creating A Child Class With Extends
To create a specialized version of a class, we use the extends keyword. This tells JavaScript that one class should inherit everything from another. The original class is often called the parent class or superclass, while the new class is called the child class or subclass.
When a child class extends a parent, it automatically receives all the non-private methods and properties defined in the parent. This establishes an "is-a" relationship. For example, a SavingsAccount is a type of Account. Using the extends keyword is the standard way to build these relationships in modern JavaScript.
In the code above, SavingsAccount is empty, but because it extends Account, any object created from it will already have an owner, a balance getter, and a toString method. This simple syntax links the two blueprints together.
Initializing The Parent With Super()
