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 14
the class Scooter
inherits the Vehicle
class.
And at lines 17 to 20
the function
getInsuranceCost
is overwritten.
line 24
the class Car
extends the
Vehicle
class.
The Car
class overwrites getInsuranceCost
function at
lines 27 - 30
.line 34
the Bicycle
class
extends Vehicle
. It doesn't overwrite
the getInsuranceCost
method. When called
(line 54
) 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 27
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 25
the class Car
inherits Vehicle
.
Car
class has 3 members -
horsePowers
defined at line 27
and also
brand
and model
(lines 7 and 8
)
due to the class extension.
Car
class constructor inherits the vehicle
constructor at
line 30
.
When car object is created (lines 54 and 58
) the code from the parent's class
constructor (lines 12 - 15
)
executes first and afterwards the code from child's constructor (lines 32 - 34
).
line 39
the representation
function of the parent class is called.
When representation
function is called for a Vehicle
object at
line 51
, only the brand is printed.
representation
function is called for a Car
object at
lines 55 and 59
, 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
.lines 5 and 6
protected
is replaced with private
,
the class Car
will have only one member -
horsePowers
and the code won't compile
due to lines 15 and 16
.