final, sealed and non-sealed subclasses
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every permitted subclass of a sealed type must say what happens below it. final stops the hierarchy there, sealed continues it with its own permits list, and non-sealed opens that one branch to anyone. The choice is per child, so one family can mix all three.
Every permitted subclass must choose final, sealed or non-sealed
A sealed parent controls only its direct children. Java still needs to know about the grandchildren, so each permitted child must carry one of three modifiers. Leave it out and javac reports sealed, non-sealed or final modifiers expected.
Example 1 · One family, three choices
import java.lang.reflect.Modifier;
abstract sealed class Vehicle permits Car, Bike, Commercial { }
sealed class Car extends Vehicle permits Sedan, Suv { }
final class Sedan extends Car { }
final class Suv extends Car { }
final class Bike extends Vehicle { }
non-sealed class Commercial extends Vehicle { }
class Tempo extends Commercial { }
class Truck extends Commercial { }
public class ThreeChoicesDemo { static String kind(Class<?> c) { if (c.isSealed()) { return "sealed"; } return Modifier.isFinal(c.getModifiers()) ? "final" : "open"; }
public static void main(String[] args) { Class<?>[] all = {Vehicle.class, Car.class, Sedan.class, Suv.class, Bike.class, Commercial.class, Tempo.class, Truck.class}; for (Class<?> c : all) { String parent = c.getSuperclass().getSimpleName(); System.out.println(c.getSimpleName() + " extends " + parent + ": " + kind(c)); } }}Vehicle extends Object: sealed Car extends Vehicle: sealed Sedan extends Car: final Suv extends Car: final Bike extends Vehicle: final Commercial extends Vehicle: open Tempo extends Commercial: open Truck extends Commercial: open
What this code does
Carissealedwith its own list, so the family below it is still closed: onlySedanandSuv.Bikeisfinal, so that branch ends.Commercialisnon-sealed, soTempoandTruckextend it with no permits list at all, and nobody had to changeVehicle. Reflection reportsCommercialitself as open.
Example 2 · A sealed branch: savings accounts with their own kinds
import java.util.List;
abstract sealed class Account permits Savings, Current { final String number; final int balance;
Account(String number, int balance) { this.number = number; this.balance = balance; }
abstract int minimumBalance();}
abstract sealed class Savings extends Account permits RegularSavings, SalarySavings { Savings(String number, int balance) { super(number, balance); }}
final class RegularSavings extends Savings { RegularSavings(String number, int balance) { super(number, balance); }
int minimumBalance() { return 5000; }}
final class SalarySavings extends Savings { SalarySavings(String number, int balance) { super(number, balance); }
int minimumBalance() { return 0; }}
final class Current extends Account { Current(String number, int balance) { super(number, balance); }
int minimumBalance() { return 25000; }}
public class SealedBranchDemo { public static void main(String[] args) { List<Account> accounts = List.of( new RegularSavings("SB-1", 3200), new SalarySavings("SB-2", 0), new Current("CA-1", 40000)); for (Account a : accounts) { boolean ok = a.balance >= a.minimumBalance(); String type = a instanceof Savings ? "savings" : "current"; System.out.println(a.number + " (" + type + ") " + (ok ? "OK" : "below minimum")); } }}SB-1 (savings) below minimum SB-2 (savings) OK CA-1 (current) OK
What this code does
Savingsisabstract sealedand permits two kinds of its own, so the whole tree is still closed: exactly three concrete account types exist.a instanceof Savingscovers both savings kinds at once. BecauseSavingsis sealed, the set of classes it covers is fixed and known.
Example 3 · Mistake: a sealed class with nothing to permit
abstract sealed class Fee permits TuitionFee, HostelFee { }
final class TuitionFee extends Fee { }
sealed class HostelFee extends Fee { }
public class EmptySealedDemo { public static void main(String[] args) { System.out.println(new TuitionFee()); }}EmptySealedDemo.java:5: error: sealed class must have subclasses
sealed class HostelFee extends Fee { }
^
1 errorWhat this code does
HostelFeeis markedsealed, but no class extends it, so there is nothing to permit. A sealed class promises a known list of children, and an empty list is an error.- If
HostelFeehas no kinds of its own, it should befinal. Usesealedonly when you also write its children, such asAcHostelFeeandNonAcHostelFee.
final: the branch ends here.sealed ... permits: the branch continues, with a known list.non-sealed: the branch is open again, on purpose.finalandsealedcannot be combined; javac calls it an illegal combination.
final class Bike extends Vehicle means no class may extend Bike. sealed class Car extends Vehicle permits Sedan, Suv means Car has its own closed list. non-sealed class Commercial extends Vehicle means any class may extend Commercial, like a normal class. Most children are final; reach for the other two only when a branch really has its own kinds.
Records are always final, so they fit naturally
A record is implicitly final. So when a record implements a sealed interface, it already satisfies the rule and needs no extra modifier: record Upi(String vpa) implements Payment { } just works. Writing sealed or non-sealed on a record is a compile error.
Example 4 · Records need no modifier: they are already final
import java.util.List;
sealed interface Payment permits Upi, Card, NetBanking { int amount();}
record Upi(String vpa, int amount) implements Payment { }
record Card(String last4, int amount) implements Payment { }
record NetBanking(String bank, int amount) implements Payment { }
public class RecordsFinalDemo { public static void main(String[] args) { List<Payment> today = List.of( new Upi("asha@okbank", 250), new Card("4242", 1800), new NetBanking("SBI", 5000)); int total = today.stream().mapToInt(Payment::amount).sum(); System.out.println("Payments: " + today.size() + ", total Rs. " + total);
for (Class<?> c : Payment.class.getPermittedSubclasses()) { System.out.println(c.getSimpleName() + " is a record: " + c.isRecord()); } }}Payments: 3, total Rs. 7050 Upi is a record: true Card is a record: true NetBanking is a record: true
What this code does
- None of the three records says
final, yet the code compiles: every record is implicitlyfinal, which is one of the three allowed choices. - Records cannot extend classes, so the sealed parent is an interface here. The interface declares
int amount(), and each record's accessor for itsamountcomponent implements it.
There is one limit. A record cannot extend any class, because it already extends java.lang.Record. So records can be children of a sealed interface, not of a sealed class. That pairing, a sealed interface with record children, is the most common shape in modern Java, and the next lesson builds on it. Enums are similar: an enum can implement a sealed interface without a modifier.
non-sealed to reopen one branch on purpose
Sometimes most of a family is fixed, but one branch must stay open. A notification library may know SMS and email for sure, yet let each app add its own channels. Make that branch non-sealed: non-sealed abstract class CustomNotification implements Notification.
Example 5 · non-sealed as an extension point
import java.util.List;
sealed interface Notification permits Sms, Email, CustomNotification { String to();
String send();}
record Sms(String to, String text) implements Notification { public String send() { return "SMS to " + to + ": " + text; }}
record Email(String to, String subject) implements Notification { public String send() { return "Email to " + to + ": " + subject; }}
// the one open branch: apps add their own channels herenon-sealed abstract class CustomNotification implements Notification { }
class WhatsAppAlert extends CustomNotification { private final String phone;
WhatsAppAlert(String phone) { this.phone = phone; }
public String to() { return phone; }
public String send() { return "WhatsApp to " + phone + ": your order is out for delivery"; }}
public class NonSealedDemo { static String channel(Notification n) { if (n instanceof Sms) { return "sms"; } else if (n instanceof Email) { return "email"; } else if (n instanceof CustomNotification) { return "custom (" + n.getClass().getSimpleName() + ")"; } throw new AssertionError("sealed: no other kind exists"); }
public static void main(String[] args) { List<Notification> outbox = List.of( new Sms("98450 12345", "OTP 4821"), new Email("riya@college.edu", "Fee receipt"), new WhatsAppAlert("98860 54321")); for (Notification n : outbox) { System.out.println(channel(n) + " -> " + n.send()); } }}sms -> SMS to 98450 12345: OTP 4821 email -> Email to riya@college.edu: Fee receipt custom (WhatsAppAlert) -> WhatsApp to 98860 54321: your order is out for delivery
What this code does
CustomNotificationisnon-sealed, soWhatsAppAlertextends it without being listed anywhere. The library's list stays three entries long, however many channels apps add.channelcan still handle every kind, but for the open branch it only knows "custom". Real work goes through the abstract methodsend(), which every subclass must write.
Apps can then write class WhatsAppAlert extends CustomNotification without asking the library to change its list.
The price is clear. Below a non-sealed class, Java no longer knows every subtype. Code that handles each kind must treat the open branch as "some custom kind" and rely on its methods, such as an abstract send(), instead of checking for specific classes. Use non-sealed as a deliberate extension point, and say why in a comment.
non-sealed is the only Java keyword with a hyphen.Interview point: sealed versus final versus abstract
These three answer different questions, which is why they can be combined in some ways and not others. abstract answers "can you create objects of this class directly?" (no). final answers "can anyone extend it?" (no). sealed answers "who may extend it?" (only the listed classes).
So abstract sealed class Account is normal and common: no plain accounts, and only the listed kinds. abstract final does not compile, because a class that cannot be created and cannot be extended is useless. final sealed does not compile either. A sealed class with no subclasses at all is also an error: sealed class must have subclasses.
abstract: nonew, children allowed (any, unless sealed).final:newallowed, no children.sealed: children allowed, only those listed.abstract sealed: the usual parent of a closed family.
Next step
Check your understanding
12 quick questions