Java 15 Tutorial
Java Other Versions Tutorials
Java 15 Useful Resources
Selected Reading
- Java 15 - Deprecation & Removals
- Java 15 - Other Enhancements
- Java 15 - Deprecation & Removals
- Java 15 - Other Changes
- Java 15 - Garbage Collectors
- Java 15 - Hidden Classes
- Java 15 - record & Sealed Classes
- Java 15 - record
- Java 15 - Text Blocks
- Java 15 - Pattern for instanceOf
- Java 15 - Sealed Classes
- Java 15 - Environment Setup
- Java 15 - Overview
- Java 15 - Home
Java Other Versions Tutorials
- Java 14 Tutorial
- Java 13 Tutorial
- Java 12 Tutorial
- Java 11 Tutorial
- Java 10 Tutorial
- Java 9 Tutorial
- Java 8 Tutorial
- Java Tutorial
Java 15 Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java 15 - Sealed Classes
Java 15 - Sealed Classes
Java 15 introduces a sealed classes as preview feature which provides a fine grained control over inheritance. Following are sapent points to consider for a sealed class −
Sealed class is declared using sealed keyword.
Sealed classes allow to declare which class can be a subtype using permits keyword.
A class extending sealed class must be declared as either sealed, non-sealed or final.
Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance.
Example
Consider the following example −
ApiTester.java
pubpc class APITester { pubpc static void main(String[] args) { Person manager = new Manager(23, "Robert"); manager.name = "Robert"; System.out.println(getId(manager)); } pubpc static int getId(Person person) { if (person instanceof Employee) { return ((Employee) person).getEmployeeId(); } else if (person instanceof Manager) { return ((Manager) person).getManagerId(); } return -1; } } abstract sealed class Person permits Employee, Manager { String name; String getName() { return name; } } final class Employee extends Person { String name; int id; Employee(int id, String name){ this.id = id; this.name = name; } int getEmployeeId() { return id; } } non-sealed class Manager extends Person { int id; Manager(int id, String name){ this.id = id; this.name = name; } int getManagerId() { return id; } }
Compile and Run the program
$javac -Xpnt:preview --enable-preview -source 14 APITester.java $java --enable-preview APITester
Output
23Advertisements