IMPLEMENTATION
OF POLYMORPHISM
AIM:
To write a java program to implement
polymorphism by creating vehicle class hierarchy using inheritance.
ALGORITHM:
1 .Create the class vehicle .Declare
its variables and define its functions.
2. Create new class car from the
base class vehicle and declare its functions
3. Create bike class from the base
class vehicle and using constructor give details about the vehicle and display the result.
4. In the main function create
objects for classes and call the corresponding function and display the result.
PROGRAM:
import.java.io.*;
class vehicle
{
String name,model,color;
void getdata()throws IOException
{
DataInputStream dis=new
DataInputStream(System.in);
System.out.println("Enter
the name:");
name=dis.readLine();
System.out.println("Enter
the model");
model=dis.readLine();
System.out.println("Enter
the color");
color=dis.readLine();
}
void putdata()
{
System.out.println("Carno="
+name);
System.out.println("Carmodel="+model);
System.out.println("Carcolor="+color);
}
}
class car
extends vehicle
{
String name1,model1,color1;
void getdata()throws IOException
{
System.out.println("\nEnter
the car details");
DataInputStream dis=new
DataInputStream(System.in);
System.out.println("Enter
the car name:");
name1=dis.readLine();
System.out.println("Enter
the car model");
model1=dis.readLine();
System.out.println("Enter the car color");
color1=dis.readLine();
}
void putdata()
{
System.out.println("Carnname="
+name1);
System.out.println("Carmodel="+model1);
System.out.println("Carcolor="+color1);
}
}
class bike
extends vehicle
{
String name2,model2,color2;
void getdata()throws IOException
{
System.out.println("Enter
the bike details");
DataInputStream dis=new
DataInputStream(System.in);
System.out.println("Enter
the bike name:");
name2=dis.readLine();
System.out.println("Enter
the bike model:");
model2=dis.readLine();
System.out.println("Enter
the bike color:");
color2=dis.readLine();
}
void putdata()
{
System.out.println("bikename="
+name2);
System.out.println("bikemodel="+model2);
System.out.println("bikecolor="+color2);
}
}
class vehicle2
{
public static void main(String
args[])throws IOException
{
vehicle v=new vehicle();
bike b=new bike();
v=b;
v.getdata();
v.putdata();
car c=new car();
v=c;
v.getdata();
v.putdata();
}
}
OUTPUT:
Enter the bike
details
Enter the bike
name:
pulsar
Enter the bike
model:
CTS125
Enter the bike
color:
red
bikename=pulsar
bikemodel=CTS125
bikecolor=red
Enter the car
details
Enter the car
name:
Enter the car
model
Lg100
Enter the car
color
silver
Carnname=Logan
Carmodel=Lg100
Carcolor=silver
RESULT
Thus the vehicle class hierarchy using inheritance was implemented.
Thus the vehicle class hierarchy using inheritance was implemented.
No comments:
Post a Comment