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 11 the class Scooter inherits the Vehicle class. And at lines 14 to 17 the function getInsuranceCost is overwritten.
  • At line 21 the class Car extends the Vehicle class. The Car class overwrites getInsuranceCost function at lines 24 - 27.
  • At line 31 the Bicycle class extends Vehicle. It doesn't overwrite the getInsuranceCost method. When called (line 47) the code from the base class is executed.

Extending functions and constructors:

Let's have a base class Vehicle and child class Car. The child class will add one more member and also extend a constructor and a function called representation.

Output:

Explanation:

  • At lines 4 and 5 instead of private the members are defined as protected. That's because we want to extend the class and inherit it's members. More details about it later in the lesson.
  • At line 21 the class Car inherits Vehicle.
  • The Car class has 3 members - horsePowers defined at line 23 and also brand and model (lines 4 and 5) due to the class extension.
  • The Car class constructor calls the Vehicle constructor at line 27 via the parent keyword. When car object is created (lines 46 and 50) the code from the parent's class constructor (lines 9 - 12) executes first and afterwards the code from child's constructor (lines 31 - 33).
  • At line 35 the representation function of the parent class is called. When representation function is called for a Vehicle object at line 43, only the brand is printed.
  • When representation function is called for a Car object at lines 47 and 51, all 3 members (make, model, horsePowers) are printed).

Private vs protected members

Both private and protected members can be accessed or modified only in a class body.

Private Members can be accessed or modified only in one class - the one they are defined in.

Protected members can be accessed or modified in the class they are defined in and the classes that extend it.

Let's look at the example:

  • Due to the extension class Car has 1 members - brand.
  • If line 14 or 17 is uncommented the code won't compile since a private or protected member cannot be accessed outside the class.
  • Public or undefined property (like randomProperty in this case) can be accessed outside the class body.