import java.io.*;
import java.util.*;
// Define an interface
interface Shape {
double calculateArea();
}
// Create a class implementing the interface
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// Create another class extending the Circle class
class Cylinder extends Circle {
private double height;
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
public double calculateVolume() {
return calculateArea() * height;
}
}
// Demonstrate exception handling
class NegativeValueException extends Exception {
public NegativeValueException(String message) {
super(message);
}
}
// Main class
public class JavaFeatureDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double circleRadius = scanner.nextDouble();
try {
if (circleRadius < 0) {
throw new NegativeValueException("Radius cannot be negative");
}
Circle circle = new Circle(circleRadius);
System.out.println("Area of the circle: " + circle.calculateArea());
System.out.print("Enter the height of the cylinder: ");
double cylinderHeight = scanner.nextDouble();
if (cylinderHeight < 0) {
throw new NegativeValueException("Height cannot be negative");
}
Cylinder cylinder = new Cylinder(circleRadius, cylinderHeight);
System.out.println("Volume of the cylinder: " + cylinder.calculateVolume());
} catch (NegativeValueException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
This program demonstrates the following Java features:
- Class and object creation
- Inheritance (
Cylinder
extendingCircle
) - Interface (
Shape
) - Exception handling (
NegativeValueException
) - Basic I/O using
Scanner
andSystem.out
- Method overriding (
calculateArea()
inCircle
andcalculateVolume()
inCylinder
)
No comments:
Post a Comment
If you have any Doubts then please let me know