Write a java program for the abstract class to find areas of different shapes.

Program Code:
import java.io.*;
abstract class Shape
{
double dim1;
double dim2;
double PI=3.14;
Shape(double a, double b)
{
dim1 = a;
dim2 = b; 
}
abstract double area(); 
}
class Rectangle extends Shape 
{
Rectangle(double a, double b) 
{
super(a, b); 
}
double area() 
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2; 
}
}
class Triangle extends Shape
{
Triangle(double a, double b)
{
super(a, b); 
}
double area() 
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2; 
}
class Circle extends Shape 
{
Circle(double a, double b)
{
super(a, b); 
}
double area()
{
System.out.println("Inside Area for Circle.");
return PI * dim1 * dim1; 
}
}
class Ellipse extends Shape 
{
Ellipse(double a, double b) 
{
super(a, b); 
}
double area() 
{
System.out.println("Inside Area for Ellipse.");
return PI * dim1 * dim2;
}
}
class Square extends Shape 
{
Square(double a, double b) 
{
super(a, b); 
}
double area() 
{
System.out.println("Inside Area for Square.");
return dim1 * dim1; 
}
}
class AbstractAreas 
{
public static void main(String args[]) 
{
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Circle c=new Circle(5,5);
Ellipse e=new Ellipse(7,7);
Square s=new Square(6,6);
Shape figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = c;
System.out.println("Area is " + figref.area());
figref = e;
System.out.println("Area is " + figref.area());
figref = s;
System.out.println("Area is " + figref.area());}
}

Output:
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Inside Area for Circle.
Area is 78.5
Inside Area for Ellipse.
Area is 153.86
Inside Area for Square.
Area is 36.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: