Overriding Methods
We noted earlier in this chapter that you can’t remove or subtract methods through inheritance. However, you can change the definition of an inherited method by overriding it.
Returning to your two classes, ClassA and ClassB, assume that you want to write your own initVar method for ClassB. You already know that ClassB will inherit the initVar method defined in ClassA, but can you make a new method with the same name to replace the inherited method? The answer is yes, and you do so simply by defining a new method with the same name. A method defined with the same name as that of a parent class replaces, or overrides, the inherited definition. Your new method must have the same return type and take the same number and type ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access