Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface ShapeOperations
- {
- double calculateArea();
- double calculatePerimeter();
- }
- // Abstract class Shape
- abstract class Shape implements ShapeOperations
- {
- // Abstract method to be implemented by subclasses
- public abstract String getShapeName();
- }
- // Circle class
- class Circle extends Shape
- {
- private double radius;
- public Circle(double radius)
- {
- this.radius = radius;
- }
- @Override
- public double calculateArea()
- {
- return Math.PI * radius * radius;
- }
- @Override
- public double calculatePerimeter()
- {
- return 2 * Math.PI * radius;
- }
- @Override
- public String getShapeName()
- {
- 30
- return "Circle";
- }
- }
- // Rectangle class
- class Rectangle extends Shape {
- private double width;
- private double height;
- public Rectangle(double width, double height) {
- this.width = width;
- this.height = height;
- }
- @Override
- public double calculateArea() {
- return width * height;
- }
- @Override
- public double calculatePerimeter() {
- return 2 * (width + height);
- }
- @Override
- public String getShapeName() {
- return "Rectangle";
- }
- }
- // Square class
- class Square extends Rectangle {
- public Square(double side) {
- super(side, side); // Call the Rectangle constructor
- }
- @Override
- public String getShapeName() {
- return "Square";
- }
- }
- // Main class to test the shapes
- public class ShapeCalculator {
- public static void main(String[] args) {
- 31
- Shape circle = new Circle(5);
- Shape rectangle = new Rectangle(4, 6);
- Shape square = new Square(3);
- // Display area and perimeter for each shape
- displayShapeInfo(circle);
- displayShapeInfo(rectangle);
- displayShapeInfo(square);
- }
- private static void displayShapeInfo(Shape shape) {
- System.out.println("Shape: " + shape.getShapeName());
- System.out.println("Area: " + shape.calculateArea());
- System.out.println("Perimeter: " + shape.calculatePerimeter());
- System.out.println("---------------------------");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement