CJ_Slip_3B

Slip No.3

B) Define an abstract class Shape with abstract methods area() and volume(). Derive abstract class Shape into two classes Cone and Cylinder. Write a java Program to calculate area and volume of Cone and Cylinder.(Use Super Keyword.)

1. Open Notepad.

2. Type the following code:

    abstract class Shape {
    abstract double area();
    abstract double volume();
    }

    class Cone extends Shape {
    private double radius;
    private double height;
    private double slantHeight;

    public Cone(double radius, double height) {
    this.radius = radius;
    this.height = height;
    this.slantHeight = Math.sqrt((radius * radius) + (height * height));
    }

    @Override
    double area() {
    // Surface Area of Cone = π * r * (r + l)
    return Math.PI * radius * (radius + slantHeight);
    }

    @Override
    double volume*() {
    // Volume of Cone = (1/3) * π * r^3 * h
    return (Math.PI * radius * radius * height) / 3;
    }
    }

    class Cylinder extends Shape {
    private double radius;
    private double height;

    public Cylinder(double radius, double height) {
    this.radius = radius;
    this.height = height;
    }

    @Override
    double area() {
    // Surface Area of Cylinder = 2 * π * r * (r + h)
    return 2 * Math.PI * radius * (radius + height);
    }

    @Override
    double volume() {
    // Volume of Cylinder = π * r^2 * h
    return Math.PI * radius * radius * height;
    }
    }

    public class ShapeDemo {
    public static void main(String[] args) {
    Cone cone = new Cone(5, 10);
    Cylinder cylinder = new Cylinder(5, 10);

    System.out.println("Cone Area: " + cone.area());
    System.out.println("Cone Volume: " + cone.volume());

    System.out.println("Cylinder Area: " + cylinder.area());
    System.out.println("Cylinder Volume: " + cylinder.volume());
    }
    }


3. Save the file with the name ShapeDemo.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Open the Command Prompt.

5. Compile the Java program by typing:
javac ShapeDemo.java

6. Run the compiled Java program by typing:
java ShapeDemo

7. output:
Cone Area: 254.160184615763
Cone Volume: 261.79938779914943
Cylinder Area: 471.23889803846896
Cylinder Volume: 785.3981633974483

No comments:

Post a Comment