Use a sealed interface and pattern matching
Description: Make a sealed interface Shape with the records Square(double side) and Circle(double radius). Write a method perimeter(Shape) with a switch expression and no default.
Hint:
- The perimeter of a circle is
2 * Math.PI * radius.
Solution
sealed interface Shape permits Square, Circle { }
record Square(double side) implements Shape { }
record Circle(double radius) implements Shape { }
public class Main {
static double perimeter(Shape s) {
return switch (s) {
case Square sq -> 4 * sq.side();
case Circle c -> 2 * Math.PI * c.radius();
};
}
public static void main(String[] args) {
System.out.println(perimeter(new Square(5)));
System.out.printf("%.2f%n", perimeter(new Circle(1)));
}
}
Output
20.0
6.28
How it works
- The interface is sealed, so the compiler knows that only
SquareandCircleexist, and the switch needs no default. - If you add a new shape, the compiler shows an error in this switch until you handle it.
Read Pattern Matching and Sealed Classes.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |