Java 15 – Record for Sealed Interfaces

  • Post author:
  • Post category:Java 15
  • Post comments:1 Comment
Java 15 - Record for Sealed Interfaces

This chapter is about Java 15 – Record for Sealed Interfaces.

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

public class APITester {
   public 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 -Xlint:preview --enable-preview -source 15 APITester.java
$java --enable-preview APITester

Output

23
Robert

In this topic we learned about Java 15 – Record for Sealed Interfaces. To know more, Click Here.

This Post Has One Comment

Leave a Reply