{"article":{"slug":"java-sealed-classes-and-exhaustive-pattern-matching","title":"Java sealed classes and exhaustive pattern matching","subtitle":null,"summary":"Neil Madden explains that exhaustive switch pattern matching over Java sealed types makes adding a new subtype a breaking change, and that consumers which aren't recompiled only fail at runtime. He argues sealed types used across module or API boundaries can introduce new ways to break code, citing the PEM-encoding JEP preview.","content_type":"blog_post","language":"en","canonical_url":"https://neilmadden.blog/2026/04/24/java-sealed-classes-and-exhaustive-pattern-matching/","author":{"name":"Neil Madden","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Neil Madden","url":"https://neilmadden.blog/","listing_slug":null,"listing":null},"topics":[{"name":"Java","slug":"java","url":"https://listedarticles.com/topics/java"},{"name":"Programming Languages","slug":"programming-languages","url":"https://listedarticles.com/topics/programming-languages"},{"name":"Software Engineering","slug":"software-engineering","url":"https://listedarticles.com/topics/software-engineering"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":642,"reading_minutes":3,"published_at":"2026-04-24T12:48:19.000Z","added_at":"2026-10-18T17:13:49.634Z","updated_at":"2026-10-18T17:13:49.634Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/java-sealed-classes-and-exhaustive-pattern-matching","markdown_url":"https://listedarticles.com/articles/java-sealed-classes-and-exhaustive-pattern-matching.md","example":false,"citation":"Neil Madden, Neil Madden. \"Java sealed classes and exhaustive pattern matching.\" 24 Apr 2026. https://neilmadden.blog/2026/04/24/java-sealed-classes-and-exhaustive-pattern-matching/ (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://neilmadden.blog/2026/04/24/java-sealed-classes-and-exhaustive-pattern-matching/"},"body_markdown":"Java 17 introduced [sealed classes](https://openjdk.org/jeps/409), which allow you to explicitly list the allowed sub-types of an interface or base class. For example, here’s a toy example using a sealed interface and records (inner classes are implicitly added to the permitted sub-types if an explicit list is not given):\n\n```\npublic sealed interface SealedType {\n    record TypeA() implements SealedType {}\n    record TypeB() implements SealedType {}\n\n    static SealedType of(String type) {\n        return switch (type) {\n            case “A” -> new TypeA();\n            case “B” -> new TypeB();\n            default -> throw new IllegalArgumentException();\n        };\n    }\n}\n```\n\nIf you are familiar with functional programming languages with algebraic datatypes, you can view this as similar to a datatype declaration in Haskell or ML:\n\n```\ndata SealedType = TypeA | TypeB\n```\n\nWe can then use this in a simple Main class:\n\n```\nvoid main(String[] args) {\n    var val = SealedType.of(args[0]);\n    System.out.println(switch (val) {\n        case SealedType.TypeA() -> “A”;\n        case SealedType.TypeB() -> “B”;\n    });\n}\n```\n\nOK, not so exciting. But one thing to note here is that we didn’t have to add a `default` clause to the switch expression in our main method. This is because sealed classes (and enums) enable *exhaustiveness checking*: the compiler knows exactly what the possible cases are, and so can check if you have covered them all. If you have, then you don’t need a `default` clause. If you forget one (and don’t have a default clause), then you get a compile-time error.\n\nThis is great when you want to ensure that all uses of some type do cover all of the cases, but it does introduce a new type of breaking change: adding a new sub-type to a sealed class/interface may break consumers of that code. For example, adding a new `TypeC` case to our example will cause the main method to fail to compile due to the missing case. So if you export a sealed type in your API then adding a new subtype is a breaking change that would require a major version bump (if you’re following SemVer).\n\n## Compile-time or runtime error?\n\nAlthough Java will produce a compile-time error for a non-exhaustive switch when you compile the consumer (main in this case), it cannot do so if the consumer is not recompiled when the sealed type changes. For example, suppose that we extend our SealedType with another case:\n\n```\npublic sealed interface SealedType {\n    record TypeA() implements SealedType {}\n    record TypeB() implements SealedType {}\n    record TypeC() implements SealedType {}\n\n    static SealedType of(String type) {\n        return switch (type) {\n            case “A” -> new TypeA();\n            case “B” -> new TypeB();\n            case “C” -> new TypeC();\n            default -> throw new IllegalArgumentException();\n        };\n    }\n}\n```\n\nIf we just recompiled SealedType.java and don’t recompile Main, then we end up with a **runtime exception** if we trigger the new case:\n\n```\n% java Main C\n\nException in thread \"main\" java.lang.MatchException\n\nat Main.main(Main.java:3)\n```\n\nHere we have the new [MatchException](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/MatchException.html) being thrown. The Javadoc notes this potential issue with separate compilation, and also some corner-cases with nulls in patterns. So even if you were hoping that using sealed classes would statically ensure that you update all consumers when a new case is added, this is not the case unless you recompile everything.\n\n## Conclusions\n\nI think for me the conclusion is that sealed types are probably most useful *within* the implementation of a component, and are less useful when exposed in the public API that a component offers to other components (eg a library). For internal use, where you typically *are* going to recompile everything together, you get the nice properties of exhaustiveness checking and higher compile-time safety guarantees. But when used across module boundaries, you may just be introducing new ways to break code, often only detectable at runtime.\n\n(I discovered these subtleties when reviewing the [preview support for PEM-encoded cryptographic objects](https://openjdk.org/jeps/524), which makes exactly this mistake of baking a sealed interface into a public API and recommend clients to pattern match against that type. A predict a very high chance of breakage if they ever want to add a new case).\n","body_html":"<p>Java 17 introduced <a href=\"https://openjdk.org/jeps/409\" rel=\"nofollow ugc noopener\">sealed classes</a>, which allow you to explicitly list the allowed sub-types of an interface or base class. For example, here’s a toy example using a sealed interface and records (inner classes are implicitly added to the permitted sub-types if an explicit list is not given):</p>\n<pre><code>public sealed interface SealedType {\n    record TypeA() implements SealedType {}\n    record TypeB() implements SealedType {}\n\n    static SealedType of(String type) {\n        return switch (type) {\n            case “A” -&gt; new TypeA();\n            case “B” -&gt; new TypeB();\n            default -&gt; throw new IllegalArgumentException();\n        };\n    }\n}</code></pre>\n<p>If you are familiar with functional programming languages with algebraic datatypes, you can view this as similar to a datatype declaration in Haskell or ML:</p>\n<pre><code>data SealedType = TypeA | TypeB</code></pre>\n<p>We can then use this in a simple Main class:</p>\n<pre><code>void main(String[] args) {\n    var val = SealedType.of(args[0]);\n    System.out.println(switch (val) {\n        case SealedType.TypeA() -&gt; “A”;\n        case SealedType.TypeB() -&gt; “B”;\n    });\n}</code></pre>\n<p>OK, not so exciting. But one thing to note here is that we didn’t have to add a <code>default</code> clause to the switch expression in our main method. This is because sealed classes (and enums) enable <em>exhaustiveness checking</em>: the compiler knows exactly what the possible cases are, and so can check if you have covered them all. If you have, then you don’t need a <code>default</code> clause. If you forget one (and don’t have a default clause), then you get a compile-time error.</p>\n<p>This is great when you want to ensure that all uses of some type do cover all of the cases, but it does introduce a new type of breaking change: adding a new sub-type to a sealed class/interface may break consumers of that code. For example, adding a new <code>TypeC</code> case to our example will cause the main method to fail to compile due to the missing case. So if you export a sealed type in your API then adding a new subtype is a breaking change that would require a major version bump (if you’re following SemVer).</p>\n<h2 id=\"compile-time-or-runtime-error\">Compile-time or runtime error?</h2>\n<p>Although Java will produce a compile-time error for a non-exhaustive switch when you compile the consumer (main in this case), it cannot do so if the consumer is not recompiled when the sealed type changes. For example, suppose that we extend our SealedType with another case:</p>\n<pre><code>public sealed interface SealedType {\n    record TypeA() implements SealedType {}\n    record TypeB() implements SealedType {}\n    record TypeC() implements SealedType {}\n\n    static SealedType of(String type) {\n        return switch (type) {\n            case “A” -&gt; new TypeA();\n            case “B” -&gt; new TypeB();\n            case “C” -&gt; new TypeC();\n            default -&gt; throw new IllegalArgumentException();\n        };\n    }\n}</code></pre>\n<p>If we just recompiled SealedType.java and don’t recompile Main, then we end up with a <strong>runtime exception</strong> if we trigger the new case:</p>\n<pre><code>% java Main C\n\nException in thread &quot;main&quot; java.lang.MatchException\n\nat Main.main(Main.java:3)</code></pre>\n<p>Here we have the new <a href=\"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/MatchException.html\" rel=\"nofollow ugc noopener\">MatchException</a> being thrown. The Javadoc notes this potential issue with separate compilation, and also some corner-cases with nulls in patterns. So even if you were hoping that using sealed classes would statically ensure that you update all consumers when a new case is added, this is not the case unless you recompile everything.</p>\n<h2 id=\"conclusions\">Conclusions</h2>\n<p>I think for me the conclusion is that sealed types are probably most useful <em>within</em> the implementation of a component, and are less useful when exposed in the public API that a component offers to other components (eg a library). For internal use, where you typically <em>are</em> going to recompile everything together, you get the nice properties of exhaustiveness checking and higher compile-time safety guarantees. But when used across module boundaries, you may just be introducing new ways to break code, often only detectable at runtime.</p>\n<p>(I discovered these subtleties when reviewing the <a href=\"https://openjdk.org/jeps/524\" rel=\"nofollow ugc noopener\">preview support for PEM-encoded cryptographic objects</a>, which makes exactly this mistake of baking a sealed interface into a public API and recommend clients to pattern match against that type. A predict a very high chance of breakage if they ever want to add a new case).</p>","headings":[{"level":2,"text":"Compile-time or runtime error?","id":"compile-time-or-runtime-error"},{"level":2,"text":"Conclusions","id":"conclusions"}]}}