{"id":5207,"date":"2024-08-29T11:03:27","date_gmt":"2024-08-29T11:03:27","guid":{"rendered":"https:\/\/www.aegissofttech.com\/insights\/?p=5207"},"modified":"2025-10-02T06:52:06","modified_gmt":"2025-10-02T06:52:06","slug":"java-sealed-classes-and-interfaces","status":"publish","type":"post","link":"https:\/\/www.aegissofttech.com\/insights\/java-sealed-classes-and-interfaces\/","title":{"rendered":"Exploring Java Sealed Classes and Interfaces: A Comprehensive Guide"},"content":{"rendered":"\n<p>Java sealed classes and interfaces, introduced in Java 15 and officially supported in <a href=\"https:\/\/www.aegissofttech.com\/insights\/what-is-java-record-benefits-features\/\" data-type=\"link\" data-id=\"https:\/\/www.aegissofttech.com\/insights\/what-is-java-record-benefits-features\/\" target=\"_blank\" rel=\"noreferrer noopener\">Java 17<\/a>, provide developers with a mechanism to control which classes or interfaces can extend or implement them. By using the <code>sealed<\/code> keyword, you can explicitly define the set of permitted subclasses or implementers, ensuring tighter control over your class hierarchy. This feature is handy in scenarios where you need to work with a fixed set of related types \u2014 like specific shapes in a geometric application or types of vehicles in a transportation system.<\/p>\n\n\n\n<p>In such cases, you can prevent new types from being introduced beyond those initially specified, maintaining consistency and preventing potential errors in your codebase. Additionally, sealed classes and interfaces improve security, maintainability, and readability by making the code&#8217;s intent explicit. By leveraging <a href=\"https:\/\/www.aegissofttech.com\/java-application-development-services.html\" target=\"_blank\" rel=\"noreferrer noopener\">Java development services<\/a>, you can effectively implement these features to enhance your applications. Let us delve deeper to understand Sealed Classes and Sealed Interfaces in Java.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Sealed Classes<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The concept of <a href=\"https:\/\/www.aegissofttech.com\/insights\/sealed-classes-in-java-benefits-syntax\/\" target=\"_blank\" rel=\"noreferrer noopener\">sealed classes in Java<\/a> was introduced in Java 15 as a preview feature and became a standard feature in Java 17.<\/li>\n\n\n\n<li>Sealed classes provide a way to restrict or limit the number of classes that can inherit the given class, thereby offering fine-grained control over the inheritance hierarchy.<\/li>\n\n\n\n<li>A sealed class can be inherited only by the classes that are allowed or permitted to access them, ensuring that the class hierarchy remains controlled and predictable.<\/li>\n\n\n\n<li>The feature introduces three new modifiers: <code>sealed<\/code>, <code>non-sealed<\/code>, and <code>permits<\/code>, which help in clearly defining the inheritance structure.<\/li>\n<\/ul>\n\n\n\n<p>In practical scenarios, sealed classes are particularly useful in domain-driven design, where a developer might want to model a domain with a limited set of variations. For instance, consider a financial application where different types of bank accounts (Savings, Checking, etc.) need to be defined. By using a sealed class, you can ensure that only these predefined account types exist, preventing the accidental introduction of invalid or unsupported account types.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2. Sealed Interfaces<\/h2>\n\n\n\n<p>Sealed interfaces extend the concept of sealed classes to interfaces, allowing developers to restrict the set of classes that can implement an interface. To seal an interface, apply the modifier <code>sealed<\/code> in its declaration, and use the <code>permits<\/code> clause to list the classes allowed to implement the sealed interface. This control is especially useful in cases where you want to limit the implementations of an interface to a known set of classes, making the code more predictable and easier to maintain.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.1 Example 1<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">public sealed class Coaching permits Vaibhav, Anjali {\n  public void info()\n  {\n\tsystem.out.println(x: \"Coaching Class\")\n  }\n}\npublic non - sealed class Anjali extends Coaching {\n  public void info() {\n\tSystem.out.println(x: \"hi friends i am Anjali\")\n  }\n}\npublic non - sealed class Vaibhav extends Coaching {\n  public void info() {\n\tSystem.out.println(x: \"hi friends i am Vaibhav\")\n  }\n}\nclass main {\n  public static void main(string args[]) {\n\tHuman h1 = new Vaibhav();\n\tHuman h2 = new Anjali();\n\th1.info();\n\th2.info();\n  }\n}\n<\/pre>\n\n\n\n<p>In this example, the <code>Coaching<\/code> class is sealed, meaning only the classes <code>Vaibhav<\/code> and <code>Anjali<\/code> are allowed to extend it. This ensures that no other classes outside those specified can inherit from <code>Coaching<\/code>, providing a controlled and well-defined hierarchy.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.2 Example 2<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">public sealed class Colors permits Red, Blue, Green {\n  \/\/ class body\n}\npublic final class Red extends Colors {\n  \/\/ class body\n}\npublic sealed class Blue extends Colors permits FilledBlue {\n  \/\/ class body\n}\npublic non - sealed class Green extends Colors {\n  \/\/ class body\n}\npublic final class FilledBlue extends Blue {\n  \/\/ class body  \n}\n<\/pre>\n\n\n\n<p>This example demonstrates a more complex inheritance hierarchy using sealed classes, where <code>Colors<\/code> is a sealed class with three permitted subclasses: <code>Red<\/code>, <code>Blue<\/code>, and <code>Green<\/code>. The <code>Red<\/code> class is final, meaning it cannot be further subclassed. The <code>Blue<\/code> class is sealed and permits only <code>FilledBlue<\/code> to extend it, while <code>Green<\/code> is non-sealed, allowing unrestricted subclassing.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.3 Key Points<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Sealed classes and interfaces provide explicit control over the inheritance hierarchy by clearly listing the classes that can extend or implement them.<\/li>\n\n\n\n<li>Final classes within this hierarchy act as endpoints in the inheritance chain, preventing further subclassing and ensuring that the hierarchy remains stable and well-defined.<\/li>\n\n\n\n<li>Non-sealed classes offer flexibility within a controlled hierarchy by allowing unrestricted subclassing beyond the permitted set, effectively ending the controlled hierarchy at that point.<\/li>\n\n\n\n<li>This structure allows developers to define a very controlled and predictable inheritance structure while still offering flexibility where needed, which is particularly beneficial in large-scale enterprise applications where maintaining consistency and preventing bugs is critical.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">2.4 Limitations<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Subclasses that are permitted must belong to the same module as the sealed class or interface, ensuring that the class hierarchy is controlled within a single module.<\/li>\n\n\n\n<li>The permitted subclasses must explicitly extend the sealed class or implement the sealed interface, providing clear visibility and control over the inheritance structure.<\/li>\n\n\n\n<li>Modifiers like <code>final<\/code>, <code>sealed<\/code>, and <code>non-sealed<\/code> must be defined in every permitted subclass or implementation, which may require careful design and planning to ensure consistency and maintainability.<\/li>\n\n\n\n<li>&nbsp;Skilled developers can ensure that sealed classes and interfaces are used to enhance your application&#8217;s architecture without creating unnecessary complications.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">3. Comparison between Sealed Classes and Interfaces<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th><strong>Sealed Classes<\/strong><\/th><th><strong>Sealed Interfaces<\/strong><\/th><\/tr><tr><td>Sealed classes restrict subclasses, and only classes that are explicitly permitted can extend a sealed class, which must belong to the same module as the sealed class.<\/td><td>Sealed interfaces restrict implementation to a predefined set of classes, offering control over the types that can implement the interface, ensuring a stable and predictable type hierarchy.<\/td><\/tr><tr><td>We typically use sealed classes when we want to define a closed set showcasing some kind of hierarchy, such as in a financial or geometric domain, where only a fixed set of types is valid.<\/td><td>Sealed interfaces are useful in complex systems where multiple inheritance and type hierarchies are used, such as in event-driven architectures or frameworks where the behavior of certain components needs to be restricted.<\/td><\/tr><tr><td>Sealed classes enforce a strict hierarchy where all subclasses must be known at compile-time, providing compile-time safety and reducing the risk of runtime errors.<\/td><td>Sealed interfaces allow for a more flexible design, enabling complex type hierarchies while still maintaining control over the types that can implement the interface, ensuring consistent behavior across implementations.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">4. Conclusion<\/h2>\n\n\n\n<p>In conclusion, sealed classes and interfaces in Java offer powerful tools for controlling and restricting inheritance and implementation hierarchies. While they share the common goal of providing control and safety, they do so in different contexts and with different levels of flexibility. Sealed classes are best suited for scenarios where a closed, well-defined type hierarchy is needed, while sealed interfaces excel in complex systems where multiple inheritance and type hierarchies are used. Both features, when used appropriately, can greatly enhance the maintainability, security, and readability of your codebase, making them valuable additions to the Java language.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>Learn how <a href=\"https:\/\/www.aegissofttech.com\/insights\/new-features-java-23\/\" target=\"_blank\" rel=\"noreferrer noopener\">Java 23 compares to Java 22<\/a>, from performance upgrades to new language features.<\/p>\n<\/blockquote>\n","protected":false},"excerpt":{"rendered":" ","protected":false},"author":12,"featured_media":5209,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[12],"tags":[921,920,923,922],"class_list":["post-5207","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-interfaces","tag-java-sealed-classes","tag-java17","tag-java21"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5207","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/comments?post=5207"}],"version-history":[{"count":17,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5207\/revisions"}],"predecessor-version":[{"id":14791,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5207\/revisions\/14791"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/media\/5209"}],"wp:attachment":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/media?parent=5207"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/categories?post=5207"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/tags?post=5207"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}