Advertisement
GamerBhai02

5. Shape Operations

Jan 16th, 2025
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | Source Code | 0 0
  1. interface ShapeOperations{
  2.     double calculateArea();
  3.     double calculatePerimeter();
  4. }
  5. abstract class Shape implements ShapeOperations{
  6.     public abstract String getShapeName();
  7. }
  8. class Circle extends Shape{
  9.     double radius;
  10.     Circle(double radius){
  11.         this.radius=radius;
  12.     }
  13.     public double calculateArea(){
  14.         return Math.PI*radius*radius;
  15.     }
  16.     public double calculatePerimeter(){
  17.         return 2*Math.PI*radius;
  18.     }
  19.     public String getShapeName(){
  20.         return "Circle";
  21.     }
  22. }
  23. class Rectangle extends Shape{
  24.     double width, height;
  25.     Rectangle(double width, double height){
  26.         this.width=width;
  27.         this.height=height;
  28.     }
  29.     public double calculateArea(){
  30.         return width*height;
  31.     }
  32.     public double calculatePerimeter(){
  33.         return 2*(width+height);
  34.     }
  35.     public String getShapeName(){
  36.         return "Rectangle";
  37.     }
  38. }
  39. class Square extends Rectangle{
  40.     double side;
  41.     Square(double side){
  42.         super(side,side);
  43.     }
  44.     public String getShapeName(){
  45.         return "Square";
  46.     }
  47. }
  48. public class ShapeCalculator{
  49.     public static void main(String[] args){
  50.         Shape c = new Circle(3);
  51.         Shape r = new Rectangle(5,2);
  52.         Shape s = new Square(4);
  53.         System.out.println(c.getShapeName());
  54.         System.out.println("Area: "+c.calculateArea());
  55.         System.out.println("Perimeter: "+c.calculatePerimeter());
  56.         System.out.println(r.getShapeName());
  57.         System.out.println("Area: "+r.calculateArea());
  58.         System.out.println("Perimeter: "+r.calculatePerimeter());
  59.         System.out.println(s.getShapeName());
  60.         System.out.println("Area: "+s.calculateArea());
  61.         System.out.println("Perimeter: "+s.calculatePerimeter());
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement