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
- Declare an interface
Shapecontaining a constantPI, aScannerobject, and an abstractarea()method. - Implement the interface in a
Circleclass to calculatePI * r * r. - Implement the interface in a
Cylinderclass to calculate2 * PI * r * h. - 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
PIvariable and theScannerobject 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 implicitlyfinal.