Menu
Topics Index
...
`

Vehicles Hierarchy - Java Example Program


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;
}
OUTPUT

Mountain Bike with registration Number APXX WWW is supported till the elevation of 3000.0 feet.

DESCRIPTION

This 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.

© meritcampus 2019

All Rights Reserved.

Open In App