Sunday, 9 February 2025

Write a Java program to calculate the volume of a cone and a cylinder using method OVERRIDING

 class Shape {

    double radius, height;


    // Constructor

    Shape(double radius, double height) {

        this.radius = radius;

        this.height = height;

    }


    // Method to be overridden

    double calculateVolume() {

        return 0;  // Default implementation

    }

}


// Cylinder class overriding calculateVolume()

class Cylinder extends Shape {

    Cylinder(double radius, double height) {

        super(radius, height);

    }


   

    double calculateVolume() {

        return Math.PI * radius * radius * height;

    }

}


// Cone class overriding calculateVolume()

class Cone extends Shape {

    Cone(double radius, double height) {

        super(radius, height);

    }


    

    double calculateVolume() {

        return (1.0 / 3) * Math.PI * radius * radius * height;

    }

}



public class VolumeCalculator {

    public static void main(String[] args) {

        Shape cylinder = new Cylinder(5, 10); 

        Shape cone = new Cone(5, 10);         


 System.out.println("Volume of Cylinder: " + cylinder.calculateVolume());

        System.out.println("Volume of Cone: " + cone.calculateVolume());

    }

}