Java Program to calculate area of circle, rectangle,square using Abstract class Shape .
Objective
Write a Java program to calculate the area of different shapes using an Abstract class.
Algorithm / Approach
- Declare an abstract class
Shapewith a constantPIand an abstract methodarea(). - Include a concrete method
display()inside the abstract class to print the calculated area. - Create a subclass
Circlethat extendsShapeand provides an implementation for thearea()method. - Create a subclass
Rectanglethat extendsShapeand provides its own implementation forarea(). - In the main method, use dynamic method dispatch to instantiate the subclasses using the parent
Shapereference.
Shape.java
import java.util.Scanner;
abstract class Shape {
final double PI=3.14;
double ar;
Scanner s=new Scanner(System.in);
public abstract void area();
public void display() {
System.out.println("Area = "+ar);
}
}
class Circle extends Shape {
public void area() {
System.out.print("Enter R: ");
int r = s.nextInt();
ar=PI*r*r;
display();
}
}
class Rectangle extends Shape {
public void area() {
System.out.print("Enter Len: ");
int l = s.nextInt();
System.out.print("Enter Breadth: ");
int b = s.nextInt();
ar = l*b;
display();
}
}
class Main{
public static void main(String[] a)
{
Shape s = new Circle();
s.area();
Shape s2 = new Rectangle();
s2.area();
}
}
}
Expected Output
Enter R: 7 Area = 153.86 Enter Len: 10 Enter Breadth: 5 Area = 50.0
Explanation of the Program
- An abstract class is a class that cannot be instantiated on its own (you cannot say
new Shape()). It exists strictly to be subclassed. - It can contain both abstract methods (methods without a body that force child classes to implement them) and concrete methods (methods with a body that child classes inherit).
- This allows you to define a common template. Every shape *must* have an area calculation (abstract), and every shape can use the exact same logic to print the area (concrete
display()method).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)