You are on page 1of 3

EX.

NO:05 IMPLEMENTATION OF POLYMORPHISM


AIM:
To design a Vehicle class hierarchy in Java. Write a test program to demonstrate
Polymorphism.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a base class named vehicle with constructor to initialize the value and
display method
STEP 3: Extend two classes namely car and lorry from the base class.
STEP 4: Define the method display under the class car by displaying all the entered values.
STEP 5: Define the method display under the class Lorry by displaying all the entered values.
STEP 6: Create an object reference
STEP 7: Create an object for the derived class and assign the object to the base class reference
STEP 8: stop the program
PROGRAM:
import java.io.*;
class Vehicle
{
String regno;
String brand;
int year;
int price;
Vehicle()
{}
Vehicle(String reg, String brd, int yr, int pr)
{
regno=reg;
brand=brd;
year=yr;
price=pr;
}
void display()
{
System.out.println("registration no: " + regno);
System.out.println("brand: " + brand);
System.out.println("year: " + year);
System.out.println("price: " + price);
}
}
class Car extends Vehicle
{
int totalseats;Car(String reg, String brd, int yr, int pr,int seat)
{
super(reg,brd,yr,pr);
totalseats=seat;
}
void display()
{
System.out.println("Car Details");
System.out.println("***********");
super.display();
System.out.println("total no of seats: " +totalseats);
}
}
class Lorry extends Vehicle
{
int MaxLoad;
Lorry(String reg, String brd, int yr, int pr, int max)
{
super(reg,brd,yr,pr);
MaxLoad=max;
}
void display()
{
System.out.println("\nLorry Details");
System.out.println("*************");
super.display();
System.out.println("maxload : " +MaxLoad+"tone");
}
}
class Bike extends Vehicle
{
int cc;
Bike(String reg, String brd, int yr, int pr, int c)
{
super(reg,brd,yr,pr);
cc=c;
}
void display()
{
System.out.println("\nBike Details");
System.out.println("************");
super.display();
System.out.println("cc : " +cc);
}
}
public class Vehicledemo
{
public static void main(String arg[])
{
Vehicle veh = new Vehicle();
Car ca=new Car("TN 10 1010","Maruti",2008,500000,5);
Lorry lo=new Lorry("TN 10 1010","Tata",2009,1000000,15);
Bike bi=new Bike("TN 10 1010","Pulsar",2013,80000,180);
veh=ca;
veh.display();
veh=lo;
veh.display();
veh=bi;
veh.display();
}
}

You might also like