Slip No.8
A) Define an Interface Shape with abstract method area(). Write a java program to calculate an area of Circle and Sphere.(use final keyword) .1. Open Notepad.
2. Define the 'Shape' Interface:
-
interface Shape {
double area(); // Abstract method to calculate area
}
3. Create Concrete Classes for 'Circle' and 'Sphere':
-
final class Circle implements Shape {
private final double radius; // Immutable radius value
// Constructor to initialize the radius
public Circle(double radius) {
this.radius = radius;
}
// Calculate and return the area of the circle
@Override
public double area() {
return Math.PI * radius * radius;
}
}
-
final class Sphere implements Shape {
private final double radius; // Immutable radius value
// Constructor to initialize the radius
public Sphere(double radius) {
this.radius = radius;
}
// Calculate and return the surface area of the sphere
@Override
public double area() {
return 4 * Math.PI * radius * radius;
}
}
4. Main Program to Test Circle and Sphere:
-
public class ShapeTest {
public static void main(String[] args) {
// Create Circle and Sphere objects
Shape circle = new Circle(5.0); // Radius of 5.0
Shape sphere = new Sphere(3.0); // Radius of 3.0
// Calculate and display the area of the Circle
System.out.println("Area of the Circle: " + circle.area());
// Calculate and display the surface area of the Sphere
System.out.println("Surface Area of the Sphere: " + sphere.area());
}
}
5. Compile the Java program by typing:
javac ShapeTest.java
6. Run the compiled Java program by typing:
java ShapeTest
No comments:
Post a Comment