Write a java program to illustrate the dynamic memory dispatch and method overriding concept with a simple example.

Program Algorithm:
Step 1: Create a class with the main function
Step 2: Create a class ‘Figure' which is extended to other classes: Rectangle, Circle, and triangle.
Step 3: In the class figure, there is a method called area and this method is given a new definition in the subclasses. So it is overridden
Step 4: Now construct the objects of the subclasses with the required attributes, that are set in the constructor. Step 5: Call the area function of all the three objects of different classes(having the same parent class).

Program Code:
import java.io.*;
class DyMemDisp
{
public static void main(String args[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
Figure f;
System.out.println("Enter the length of rectangle:");
float l=Float.parseFloat(b.readLine());
System.out.println("Enter the breadth of rectangle:");
float g=Float.parseFloat(b.readLine());
Rectangle r=new Rectangle(l,g);
System.out.println("Enter the radius of circle:");
float ra=Float.parseFloat(b.readLine());
Circle c=new Circle(ra);
System.out.println("Enter the base of triangle:");
float br=Float.parseFloat(b.readLine());
System.out.println("Enter the height of triangle:");
float he=Float.parseFloat(b.readLine());
Triangle t=new Triangle(br,he);
f=r;
f.area();
f=c;
f.area();
f=t;
f.area();
}
}
class Figure
{
float d1,d2;
Figure(float a,float b)
{
d1=a;
d2=b;
}
void area()
{}
}
class Rectangle extends Figure
{
float l,ba;
Rectangle(float a,float b)
{
super(a,b);
l=a;
ba=b;
}
void area()
{
System.out.println("Area of rectangle="+(l*ba));
}
}
class Circle extends Figure
{
float r;
Circle(float a)
{
super(a,0);
r=a;
}
void area()
{
System.out.println("Area of circle="+(3.14f*r*r));
}
}
class Triangle extends Figure
{
float ba,h;
Triangle(float a,float b)
{
super(a,b);
ba=a;
h=b;
}
void area()
{
System.out.println("Area of Triangle="+(0.5f*ba*h));
}
}


Sample Inputs and Outputs:
Enter the length of rectangle:
5
Enter the breadth of rectangle:
2
Enter the radius of circle:
2
Enter the base of triangle:
2
Enter the height of triangle:
8
Area of rectangle=10.0
Area of circle=12.56
Area of Triangle=8.0
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: