Slip No 8 Q A

Q. Define an Interface Shape with abstract method area(). Write a java program to calculate an area of Circle and Sphere.(use final keyword) [15 M]

import java.util.Scanner;

// Interface Shape
interface Shape {
    double area();
}

// Circle class
class Circle implements Shape {
    final double PI = 3.14;   // final keyword
    double r;

    Circle(double r) {
        this.r = r;
    }

    public double area() {
        return PI * r * r;
    }
}

// Sphere class
class Sphere implements Shape {
    final double PI = 3.14;   // final keyword
    double r;

    Sphere(double r) {
        this.r = r;
    }

    public double area() {
        return 4 * PI * r * r;   // surface area of sphere
    }
}

// Main class
public class InterfaceShapeDemo {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter radius of Circle: ");
        double rc = sc.nextDouble();

        System.out.print("Enter radius of Sphere: ");
        double rs = sc.nextDouble();

        Circle c = new Circle(rc);
        Sphere s = new Sphere(rs);

        System.out.println("\nArea of Circle = " + c.area());
        System.out.println("Surface Area of Sphere = " + s.area());

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top