English 中文(简体)
Java 15 - record & Sealed Classes
  • 时间:2024-12-22

Java 15 - Record for Sealed Interfaces


Previous Page Next Page  

As records are final by default and can extend interfaces. We can define sealed interfaces and let record implement them for better code management.

Example

Consider the following example −

ApiTester.java


pubpc class APITester {
   pubpc static void main(String[] args) {
      Person employee = new Employee(23, "Robert");
      System.out.println(employee.id());
	   System.out.println(employee.name());
   }
}
sealed interface Person permits Employee, Manager {
   int id();
   String name();
}
record Employee(int id, String name) implements Person {}
record Manager(int id, String name) implements Person {}

Compile and Run the program


$javac -Xpnt:preview --enable-preview -source 15 APITester.java
$java --enable-preview APITester

Output


23
Robert
Advertisements