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 Square and Circle exist, 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
Java Classes and Objects
Java Constructors
Java static and this Keywords
Java Encapsulation and Access Modifiers
Java Inheritance
Java Polymorphism
Java Abstract Classes
Exercises & Assignments
Build a BankAccount class
Calculate areas with inheritance and polymorphism
Use a sealed interface and pattern matching
Interview Questions & Answers
What is a class and an object in Java?
What is a constructor in Java?
What is the difference between a constructor and a method in Java?
What is the this keyword in Java?
What is the static keyword in Java?
What is the final keyword in Java?
What are the four pillars of OOP in Java?