Created
July 31, 2024 19:33
-
-
Save littleli/3d0aa879ae5a86e34a45d548ccc20318 to your computer and use it in GitHub Desktop.
ADT in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed interface Shape permits Shape.Rectangle, Shape.Square, Shape.Circle { | |
record Circle(double radius) implements Shape {} | |
record Rectangle(double length, double width) implements Shape {} | |
record Square(double side) implements Shape {} | |
} | |
public class Main { | |
public static double calculateArea(Shape shape) { | |
return switch (shape) { | |
case Shape.Circle(var radius) -> Math.PI * Math.pow(radius, 2); | |
case Shape.Rectangle(var length, var width) -> length * width; | |
case Shape.Square(var side) -> Math.pow(side, 2); | |
}; | |
} | |
public static void main(String[] args) { | |
var circle = new Shape.Circle(5.0); | |
var rectangle = new Shape.Rectangle(4.0, 6.0); | |
var square = new Shape.Square(3.0); | |
System.out.println("Circle area: " + calculateArea(circle)); | |
System.out.println("Rectangle area: " + calculateArea(rectangle)); | |
System.out.println("Square area: " + calculateArea(square)); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment