5th Exp in Java For Rec and Observation
5th Exp in Java For Rec and Observation
No:5 Write a Java Program to create an abstract class named Shape that
contains two integers and an empty method named printArea(). Provide
three classes named Rectangle, Triangle and Circle such that each one of
the classes extends the class Shape. Each one of the classes contains only
the method printArea( ) that prints the area of the given shape. Solve the
above problem using an interface
AIM:
To write a Java program to calculate the area of rectangle, circle and triangle by implementing
the interface shape.
ALGORITHM:
Step 1: Start the program.
Step 2: Create an interface named shape that contains an empty methodnamed printArea().
Step 3: Create three classes named rectangle, triangle and circle such that each one of the classes
implements the class Shape.
Step 4: Each of the class should provide the implementation for the method printArea().
Step 5: In printAree() method get the input from user and calculate the area of rectangle, circle
and triangle.
Step 6: In the TestAreaclass, create the objects for the three classes and invoke the
MethodprintArea() and display the area values of the different shapes.
Step 7: Stop the program.
PROGRAM:
TestArea.java
import java.util.Scanner;
interface Shape
{
public void printArea();
}
class Rectangle implements Shape
{
public void printArea()
{
System.out.println("\t\tCalculating Area of Rectangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter length: ");
int a=input.nextInt();
System.out.print("\nEnter breadth: ");
int b=input.nextInt();
int area=a*b;
System.out.println("Area of Rectangle: "+area);
}
}
class Triangle implements Shape
{
public void printArea()
{
System.out.println("\t\tCalculating Area of Triangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter height: ");
int a=input.nextInt();
System.out.print("\nEnter breadth: ");
int b=input.nextInt();
double area=0.5*a*b;
System.out.println("Area of Triangle: "+area);
}
}
class Circle implements Shape
{
public void printArea()
{
System.out.println("\t\tCalculating Area of Circle");
Scanner input=new Scanner(System.in);
System.out.print("Enter radius: ");
int a=input.nextInt();
double area=3.14*a*a;
System.out.println("Area of Circle: "+area);
}
}
public class TestArea
{
public static void main(String[] args)
{
Shape obj;
obj=new Rectangle();
obj.printArea();
obj=new Triangle();
obj.printArea();
obj=new Circle();
obj.printArea();
}
}
OUTPUT:
Calculating Area of Rectangle
Enter length: 14
Enter breadth: 24
Area of Rectangle: 336
Calculating Area of Triangle
Enter height: 45
Enter breadth: 32
Area of Triangle: 720.0
Calculating Area of Circle
Enter radius: 5
Area of Circle: 78.5
RESULT:
Thus, the Java program to calculate the area of rectangle, circle and triangle using the
concept of interface was developed and executed successfully.