As discussed in
Java Class Inheritance Java supports inheritance to provide a hierarchy for class definition and hence avoiding duplicate code and increasing maintainability. There is no limit on the levels of hierarchy. We could have class
D
extend from class
C
, which in turn extends from class
B
, which in turn extends from class
A
.
e.g., MountainBike
extends from
Bike
,
Bike
extends from
RegisteredVehicle
,
RegisteredVehicle
extends from
Vehicle
.
The following program shows how we could implement
multi-level inheritance.
Vehicles Hierarchy
class TestVehiclesHierarchy
{
public static void main(String arg[])
{
MountainBike mb = new MountainBike();
mb.numberOfWheels = 2;
mb.registrationNumber = "APXX WWW";
mb.hasHelmet = true;
mb.maxElevation = 3000.0;
System.out.print("Mountain Bike with registration Number " + mb.registrationNumber);
System.out.println(" is supported till the elevation of " + mb.maxElevation + " feet.");
}
}
class Vehicle
{
int numberOfWheels;
}
class RegisteredVehicle extends Vehicle
{
String registrationNumber;
}
class Bike extends RegisteredVehicle // LINE A
{
boolean hasHelmet;
}
class MountainBike extends Bike
{
double maxElevation;
}
class Car extends RegisteredVehicle
{
boolean hasAC;
}
class Cycle extends Vehicle
{
boolean hasBackSeat;
}
OUTPUTMountain Bike with registration Number APXX WWW is supported till the elevation of 3000.0 feet.
DESCRIPTIONThis program shows how to implement multi level inheritance. Initially Vehicle
class is defined. RegisteredVehicle
extends from Vehicle
, Bike
extends from RegisteredVehicle
and MountainBike
extends from Bike
. So a MountainBike
is a Bike
, which in turn is a RegisteredVehicle
, which in turn is a Vehicle
. We also defined Car
which extends from RegisteredVehicle
and Cycle
which extends from Vehicle
.
THINGS TO TRY
- Add
double maxSpeed
to Vehicle
and see if we can initialize and print in the main
method.
- Change
LINE A
from class Bike extends RegisteredVehicle
to class Bike extends RegisteredVehicle, Cycle
and see what compilation error you get.
The class hierarchy in the above program when shown in a diagram will look like.
Please note that
multi-level inheritance is different from
multiple inheritance. Multiple inheritance which means inheriting from two classes is not supported in the Java. Although C++ supports multiple inheritance, it is intentionally not supported in java, since it adds lots of complexity.