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 6
the class Scooter
inherits the Vehicle
class.
And at lines 8 and 9
the function
getInsuranceCost
is overwritten.
line 13
the class Car
extends the
Vehicle
class.
The Car
class overwrites getInsuranceCost
function at
lines 15 - 16
.line 19
the Bicycle
class
extends Vehicle
. It doesn't overwrite
the getInsuranceCost
method. When called
(line 32
) the code from the base class is executed.
A child's class constructor can call parent's class 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:
line 11
the class Car
inherits Vehicle
.
Car
class constructor calls the Vehicle
constructor at
line 13
via the super
keyword.
When car object is created (lines 28 and 32
) the code from the parent's class
constructor (lines 3 - 6
)
executes first and afterwards the code from child's constructor (lines 13 - 16
).
line 19
the representation
function of the parent class is called.
When representation
function is called for a Vehicle
object at
line 25
, only the brand is printed.
representation
function is called for a Car
object at
lines 29 and 33
, all 3 properties (make, model, horsePowers) are printed.