Slip No.3
B) 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 class Shape {
double radius, height;
// Constructor
Shape(double radius, double height) {
this.radius = radius;
this.height = height;
}
// Abstract methods
abstract void area();
abstract void volume();
}
// Cone class extending Shape
class Cone extends Shape {
Cone(double radius, double height) {
super(radius, height);
}
void area() {
double slantHeight = Math.sqrt((radius * radius) + (height * height));
double area = Math.PI * radius * (radius + slantHeight);
System.out.println("Cone Area: " + area);
}
void volume() {
double volume = (Math.PI * radius * radius * height) / 3;
System.out.println("Cone Volume: " + volume);
}
}
// Cylinder class extending Shape
class Cylinder extends Shape {
Cylinder(double radius, double height) {
super(radius, height);
}
void area() {
double area = 2 * Math.PI * radius * (radius + height);
System.out.println("Cylinder Area: " + area);
}
void volume() {
double volume = Math.PI * radius * radius * height;
System.out.println("Cylinder Volume: " + volume);
}
}
// Main class
public class ShapeTest {
public static void main(String[] args) {
Cone cone = new Cone(5, 10);
System.out.println("=== Cone ===");
cone.area();
cone.volume();
Cylinder cylinder = new Cylinder(5, 10);
System.out.println("\n=== Cylinder ===");
cylinder.area();
cylinder.volume();
}
}
4. Open the Command Prompt.
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