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
Initializing The Parent With Super()
When you create a child class and give it its own constructor, there is a very important rule you must follow: you must call super() before you can use the this keyword. The super function tells JavaScript to run the constructor of the parent class first. This ensures that the parent has a chance to set up its own properties, like the owner and the #balance, before the child class tries to add its own specific data.
If you try to use this before calling super(), your code will crash with a reference error. Once super() is called, you can then proceed to set up any properties that are unique to the child class, such as an interest rate.
In this example, the SavingsAccount constructor takes three arguments. It passes the owner and balance up to the Account constructor by calling super(owner, balance). After that is finished, it sets the private #interestRate property that only exists for savings accounts. This sequence ensures the entire object is built correctly from the ground up.
