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 15 to 18 the function getInsuranceCost is overwritten.
  • At line 22 the class Car extends the Vehicle class. The Car class overwrites getInsuranceCost function at lines 26 - 29.
  • At line 33 the Bicycle class extends Vehicle. It doesn't overwrite the getInsuranceCost method. When called (line 52) 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 line 3 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 22 the class Car inherits Vehicle.
  • The Car class has 3 members - horsePowers defined at line 25 and also brand and model (lines 4 and 5) due to the class extension.
  • The Car class constructor calls the Vehicle constructor at line 30 via the super keyword. When car object is created (lines 52 and 56) the code from the parent's class constructor (lines 10 - 13) executes first and afterwards the code from child's constructor (lines 31 - 33).
  • At line 38 the representation function of the parent class is called. When representation function is called for a Vehicle object at line 49, only the brand is printed.
  • When representation function is called for a Car object at lines 57 and 61, 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 3 members - brand, model and horsePowers.
  • If at line 3 we replace protected with private, the class Car will have only one member - horsePowers and the code won't compile due to lines 16 and 17.