Class Inheritance Basics

Class Inheritance is a way to extend a class. The new class (child class) builds or overwrites logic from the parent class (super class).

The syntax for class extension is:

Overwriting methods:

Overwritten method is a method that has been inherited from the parent but it's logic is changed in the child.

Syntax for overwriting function:

Let's have a base class Vehicle and child classes - Car, Scooter, Bicycle. We'll set a simplified formula for the insurance cost.

Output:

Explanation:

  • At line 9 the class Scooter inherits the Vehicle class. And at lines 12 to 15 the function getInsuranceCost is overwritten.
  • At line 19 the class Car extends the Vehicle class. The Car class overwrites getInsuranceCost function at lines 22 - 25.
  • At line 29 the Bicycle class extends Vehicle. It doesn't overwrite the getInsuranceCost method. When called (line 45) the code from the base class is executed.

Extending functions and constructors:

When constructor for a child class is written, it must call the parent's constructor via the super keyword.

Let's have a base class Vehicle and child class Car. The child class will extend it's parent constructor and a function called representation.

Output:

Explanation:

  • At line 13 the class Car inherits Vehicle.
  • The Car class constructor calls the Vehicle constructor at line 15 via the super keyword. When car object is created (lines 31 and 35) the code from the parent's class constructor (lines 3 - 5) executes first and afterwards the code from child's constructor (lines 21 - 23).
  • When representation function is called for a Vehicle object at line 28, only the brand is printed.
  • When representation function is called for a Car object at lines 32 and 36, all 3 properties (make, model, horsePowers) are printed.