Skip to main content

ProwessApps

Learn · Practice · Excel

Create an Interface with name "Shape", WAP to calculate the area of circle and cylinder.

Java Code Example — Abstract and Interface Programs

ADVERTISEMENT

Create an Interface with name "Shape", WAP to calculate the area of circle and cylinder.

Objective

Create a Shape interface to calculate the area of geometric figures.

Algorithm / Approach

  1. Declare an interface Shape containing a constant PI, a Scanner object, and an abstract area() method.
  2. Implement the interface in a Circle class to calculate PI * r * r.
  3. Implement the interface in a Cylinder class to calculate 2 * PI * r * h.
  4. In main, instantiate both classes and invoke their area methods.
Circle.java
import java.util.*;
interface Shape {
 double PI= 3.14;
 Scanner s=new Scanner(System.in);
 public void area();
}
class Circle implements Shape {
 public void area() {
 // s = new Scanner(System.in);
  System.out.print("Enter Radius: ");
  double r = s.nextDouble();
  double ar = PI*r*r;
  System.out.println("Circle Area- "+ar);
 }
}
class Cylinder implements Shape {
 public void area() {
  System.out.print("Enter Radius: ");
  double r = s.nextDouble();
  System.out.print("Enter Height: ");
  double h = s.nextDouble();
  double ar =2*PI*r*h;
  System.out.print("Cylinder Area- "+ar);
 }
}
class Test{
 public static void main(String[] a) 
 {
  Shape s = new Circle();
  s.area();
  Shape s2 = new Cylinder();
  s2.area();
 }
}

Expected Output

Enter Radius: 7
Circle Area- 153.86
Enter Radius: 5
Enter Height: 7
Cylinder Area- 219.8

Explanation of the Program

  • Any variable declared inside an interface is automatically implicitly public static final.
  • This means that the PI variable and the Scanner object belong to the interface itself, not to any specific object, and cannot be changed (they are constants).
  • Because the scanner is static and shared, both the Circle and Cylinder classes can use it to read input without having to instantiate their own Scanner objects.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Trying to modify an interface variable (like PI = 3.14159) inside an implementing class. It will cause a compilation error because it is implicitly final.
ADVERTISEMENT