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 15
the class Scooter
inherits the Vehicle
class.
And at lines 19 to 22
the function
getInsuranceCost
is overwritten.
line 26
the class Car
extends the
Vehicle
class.
The Car
class overwrites getInsuranceCost
function at
lines 30 - 33
.line 37
the Bicycle
class
extends Vehicle
. It doesn't overwrite
the getInsuranceCost
method. When called
(line 55
) 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:
line 29
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 34
the class Car
inherits Vehicle
.
Car
class has 3 members -
horsePowers
defined at line 30
and also
brand
and model
(lines 9 and 10
)
due to the class extension.
Car
class constructor inherits the vehicle
constructor at
line 32
.
When car object is created (lines 56 and 60
) the code from the parent's class
constructor (lines 15 - 18
)
executes first and afterwards the code from child's constructor (lines 36 - 38
).
line 43
the representation
function of the parent class is called.
When representation
function is called for a Vehicle
object at
line 53
, only the brand is printed.
representation
function is called for a Car
object,
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 3 members - brand
,
model
and horsePowers
.line 8
we replace protected
with private
,
the class Car
will have only one member -
horsePowers
and the code won't compile
due to lines 21 and 22
.