Understanding Sealed Classes in Java JDK 15
This article explains Java JDK 15’s sealed class feature, showing how to declare sealed classes, the required permits clause, and the necessary final, sealed, or non‑sealed modifiers for subclasses, illustrated with complete code examples.
JDK 15 introduced sealed classes, allowing a class to restrict which other classes may extend it by using the sealed modifier together with a permits clause.
When a class is declared sealed, each subclass must be declared as final , sealed , or non-sealed ; otherwise the compiler reports an error.
Below is a typical inheritance hierarchy without sealed classes:
public class Person { }
class Teacher extends Person { } // teacher
class Student extends Person { } // student
class MiddleSchoolStudent extends Student { } // middle school student
class GraduateStudent extends Student { } // graduate student
class Worker extends Person { } // worker
class RailWayWorker extends Worker { } // railway workerAttempting to mark Person as sealed without specifying permitted subclasses results in a compilation error:
public sealed class Person { }
class Teacher extends Person { } // teacher
class Student extends Person { } // student
class MiddleSchoolStudent extends Student { } // middle school student
class GraduateStudent extends Student { } // graduate student
class Worker extends Person { } // worker
class RailWayWorker extends Worker { } // railway workerTo correctly inherit from a sealed class, the permits clause must list all allowed subclasses, and each listed subclass must be declared final , sealed , or non-sealed :
public sealed class Person permits Teacher, Student, Worker { }
final class Teacher extends Person { } // teacher
sealed class Student extends Person permits MiddleSchoolStudent, GraduateStudent { }
final class MiddleSchoolStudent extends Student { } // middle school student
final class GraduateStudent extends Student { } // graduate student
non-sealed class Worker extends Person { } // worker
class RailWayWorker extends Worker { } // railway workerSigh, sealed classes can be inherited now, it overturns my code‑learning worldview.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.