0% found this document useful (0 votes)
14 views2 pages

P 8 A Find Areas

This Java program implements runtime polymorphism using a Figure superclass and Rectangle and Triangle subclasses that override the area method. The program creates Figure, Rectangle, and Triangle objects and uses a Figure reference variable to call their area methods at runtime based on the actual object type.

Uploaded by

Vali Bhasha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

P 8 A Find Areas

This Java program implements runtime polymorphism using a Figure superclass and Rectangle and Triangle subclasses that override the area method. The program creates Figure, Rectangle, and Triangle objects and uses a Figure reference variable to call their area methods at runtime based on the actual object type.

Uploaded by

Vali Bhasha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

//8a) Write a JAVA program that implements Runtime polymorphism

// Using run-time polymorphism.


class Figure //super class
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
double area()
{
System.out.println("Area for Figure is undefined.");
return 0;
}
}

class Rectangle extends Figure


{
Rectangle(double a, double b)
{ super(a, b); }

// override area for rectangle


double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure


{
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}

class FindAreas
{
public static void main(String args[])
{
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);

Figure figref; //super class ref variable

figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());

figref = f;
System.out.println("Area is " + figref.area());
}
}

You might also like