Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to calculate area of circle, rectangle,square using Abstract class Shape .

Java Code Example — Abstract and Interface Programs

ADVERTISEMENT

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

  1. Declare an abstract class Shape with a constant PI and an abstract method area().
  2. Include a concrete method display() inside the abstract class to print the calculated area.
  3. Create a subclass Circle that extends Shape and provides an implementation for the area() method.
  4. Create a subclass Rectangle that extends Shape and provides its own implementation for area().
  5. In the main method, use dynamic method dispatch to instantiate the subclasses using the parent Shape reference.
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)
ADVERTISEMENT