Q.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.) [25 M]
import java.util.Scanner;
// Abstract class Shape
abstract class Shape {
double r, h;
// Constructor using super concept
Shape(double r, double h) {
this.r = r;
this.h = h;
}
abstract double area();
abstract double volume();
}
// Cone class
class Cone extends Shape {
Cone(double r, double h) {
super(r, h); // calling parent constructor
}
double area() {
double l = Math.sqrt(r*r + h*h); // slant height
return Math.PI * r * (r + l);
}
double volume() {
return (Math.PI * r * r * h) / 3;
}
}
// Cylinder class
class Cylinder extends Shape {
Cylinder(double r, double h) {
super(r, h); // calling parent constructor
}
double area() {
return 2 * Math.PI * r * (r + h);
}
double volume() {
return Math.PI * r * r * h;
}
}
// Main class
public class ShapeDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter radius and height for Cone: ");
double r1 = sc.nextDouble();
double h1 = sc.nextDouble();
System.out.print("Enter radius and height for Cylinder: ");
double r2 = sc.nextDouble();
double h2 = sc.nextDouble();
Cone c1 = new Cone(r1, h1);
Cylinder c2 = new Cylinder(r2, h2);
System.out.println("\nCone Area = " + c1.area());
System.out.println("Cone Volume = " + c1.volume());
System.out.println("\nCylinder Area = " + c2.area());
System.out.println("Cylinder Volume = " + c2.volume());
sc.close();
}
}