Advertisement
GamerBhai02

Abstract and interface (area and perimeter)

Nov 11th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.91 KB | Source Code | 0 0
  1. interface ShapeOperations
  2. {
  3.  double calculateArea();
  4.  double calculatePerimeter();
  5. }
  6. // Abstract class Shape
  7. abstract class Shape implements ShapeOperations
  8. {
  9.  // Abstract method to be implemented by subclasses
  10.  public abstract String getShapeName();
  11. }
  12. // Circle class
  13. class Circle extends Shape
  14. {
  15.  private double radius;
  16.  public Circle(double radius)
  17. {
  18.  this.radius = radius;
  19.  }
  20.  @Override
  21.  public double calculateArea()
  22. {
  23.  return Math.PI * radius * radius;
  24.  }
  25.  @Override
  26.  public double calculatePerimeter()
  27. {
  28.  return 2 * Math.PI * radius;
  29.  }
  30.  @Override
  31.  public String getShapeName()
  32. {
  33. 30
  34.  return "Circle";
  35.  
  36. }
  37. }
  38. // Rectangle class
  39. class Rectangle extends Shape {
  40.  private double width;
  41.  private double height;
  42.  public Rectangle(double width, double height) {
  43.  this.width = width;
  44.  this.height = height;
  45.  
  46. }
  47.  @Override
  48.  public double calculateArea() {
  49.  return width * height;
  50.  
  51. }
  52.  @Override
  53.  public double calculatePerimeter() {
  54.  return 2 * (width + height);
  55.  
  56. }
  57.  @Override
  58.  public String getShapeName() {
  59.  return "Rectangle";
  60.  
  61. }
  62. }
  63. // Square class
  64. class Square extends Rectangle {
  65.  public Square(double side) {
  66.  super(side, side); // Call the Rectangle constructor
  67.  
  68. }
  69.  @Override
  70.  public String getShapeName() {
  71.  return "Square";
  72.  
  73. }
  74. }
  75. // Main class to test the shapes
  76. public class ShapeCalculator {
  77.  public static void main(String[] args) {
  78. 31
  79.  Shape circle = new Circle(5);
  80.  Shape rectangle = new Rectangle(4, 6);
  81.  Shape square = new Square(3);
  82.  // Display area and perimeter for each shape
  83.  displayShapeInfo(circle);
  84.  displayShapeInfo(rectangle);
  85.  displayShapeInfo(square);
  86.  }
  87.  private static void displayShapeInfo(Shape shape) {
  88.  System.out.println("Shape: " + shape.getShapeName());
  89.  System.out.println("Area: " + shape.calculateArea());
  90.  System.out.println("Perimeter: " + shape.calculatePerimeter());
  91.  System.out.println("---------------------------");
  92.  }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement