abstract class Shape {
abstract double area(); // Abstract method to calculate area
abstract double perimeter(); // Abstract method to calculate perimeter
void display() {
System.out.println("This is a shape.");
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
@Override
double perimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double area() {
return length * width;
}
@Override
double perimeter() {
return 2 * (length + width);
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Circle circle = new Circle(5);
System.out.println("Area of circle: " + circle.area());
System.out.println("Perimeter of circle: " + circle.perimeter());
Rectangle rectangle = new Rectangle(4, 6);
System.out.println("Area of rectangle: " + rectangle.area());
System.out.println("Perimeter of rectangle: " + rectangle.perimeter());
circle.display();
rectangle.display();
}
}
No comments:
Post a Comment