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:
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:
line 11 the class Scooter inherits the Vehicle class.
And at lines 14 to 17 the function
getInsuranceCost is overwritten.
line 21 the class Car extends the
Vehicle class.
The Car class overwrites getInsuranceCost function at
lines 24 - 27.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.
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:
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.
line 21 the class Car inherits Vehicle.
Car class has 3 members -
horsePowers defined at line 23 and also
brand and model (lines 4 and 5)
due to the class extension.
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).
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.
representation function is called for a Car object at
lines 47 and 51, all 3 members (make, model, horsePowers) are printed).
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:
Car has 1 members - brand.line 14 or 17 is uncommented the code won't compile since
a private or protected member cannot be accessed outside the class.randomProperty in this case)
can be accessed outside the class body.