Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Sealed Classes and Interfaces

sealed interface Payment permits Card, Wallet, Cash is a guest list javac enforces, so a Voucher is a compile error. Account shows final, sealed and non-sealed children, Delivery records each carry their own data and fee, and a switch over Payment needs no default.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Close a type family with sealed and permits so javac rejects anything else
  • Choose final, sealed or non-sealed for each permitted subclass
  • Model real cases as records under one sealed interface
  • Write a switch over a sealed type that needs no default

Before you start

  • Java records
  • Java interfaces

A sealed class is a class family with a fixed guest list. You write the list, and javac, the Java compiler, enforces it.

An interface is open to anyone

Say a Payment interface has three planned kinds: Card, Wallet and Cash. But any class anywhere can implement an interface: GiftCard, Barter, Coupon. Nobody can list every kind of payment. That's what sealed fixes.

package org.studyeasy.s05l02;

import java.util.List;

public class Ex01_SealedPayment {
    // The guest list: only these three types may implement Payment
    sealed interface Payment permits Card, Wallet, Cash {}

    // Records are final already, so they need no extra modifier
    record Card(String holder, double amount) implements Payment {}
    record Wallet(String walletId, double amount) implements Payment {}
    record Cash(double amount) implements Payment {}

    public static void main(String[] args) {
        List<Payment> today = List.of(
                new Card("Emma Clarke", 250.0),
                new Wallet("liam.w@wallet", 80.0),
                new Cash(40.0));
        for (Payment p : today) {
            System.out.println(p);
        }
    }
}
Card[holder=Emma Clarke, amount=250.0]
Wallet[walletId=liam.w@wallet, amount=80.0]
Cash[amount=40.0]

sealed and permits give the full list: only Card, Wallet and Cash may implement Payment. All three are records, which are final already, so they join with no extra keyword. Add record Voucher(double amount) implements Payment {} and javac refuses: class is not allowed to extend sealed class: Payment (as it is not listed in its 'permits' clause). It's a compile error, not a surprise at run time. To add a type, edit the permits line first.

Sealed classes too

// A sealed class names its subclasses...
static sealed abstract class Account permits Savings, Loan, Current {}

// ...and each one decides how the family goes on
static final class Savings extends Account {}                 // ends here
static sealed class Loan extends Account permits HomeLoan {}  // new list
static final class HomeLoan extends Loan {}
static non-sealed class Current extends Account {}            // open again
static class BusinessCurrent extends Current {}               // allowed
Savings extends Account
HomeLoan extends Loan
BusinessCurrent extends Current
Sealed Account permits Savings, Loan and Current. Savings is final, so the family ends there. Loan is sealed with its own list, permits HomeLoan, which is final. Current is non-sealed, so BusinessCurrent or any other class may extend it. sealed Account final Savings sealed Loan non-sealed Current final HomeLoan BusinessCurrent, anyone family ends here
Each permitted subclass picks exactly one: final, sealed or non-sealed.

This part is slightly tricky. Savings is final, so nobody extends it. Loan is sealed again, with its own list, so HomeLoan may extend Loan (but not Account directly). Current is non-sealed, which opens it up again, so BusinessCurrent extends it without permission. Leave all three off a permitted class and javac says sealed, non-sealed or final modifiers expected. Records need none, since they're final.

Model the real cases

// Every delivery option, and each one carries only the data it needs
sealed interface Delivery permits Standard, Express, Pickup {
    default double fee() { return 0; }             // Pickup is free
}
record Standard(int km) implements Delivery {
    public double fee() { return 30 + 2 * km; }
}
record Express(int km) implements Delivery {
    public double fee() { return 99 + 5 * km; }
}
record Pickup(String store) implements Delivery {}

List<Delivery> orders = List.of(new Standard(12), new Express(4),
        new Pickup("Downtown"));
for (Delivery d : orders) {
    System.out.println(d + " -> fee " + d.fee());
}
Standard[km=12] -> fee 54.0
Express[km=4] -> fee 119.0
Pickup[store=Downtown] -> fee 0.0

The sealed line lists every way an order can travel, and each case holds only its own data: kilometres for Standard and Express, a store name for Pickup. Pickup has no fee of its own, so it uses the default, 0. One call, d.fee(), and each object gives the right fee (30 + 2 × 12 is 54). This is the kind of sealed interface you'll see most often.

Why not an enum? An enum gives a fixed set of values, one object each with the same fields, so there's nowhere for 12 km or a store name to go. A sealed interface gives a fixed set of types, and each object carries its own data. Same shape for every case: enum. Different data, closed list: sealed with records.

A switch with no default

// No default branch: javac checks that every permitted type has a case
static String receipt(Payment p) {
    return switch (p) {
        case Card c -> c.holder() + " paid " + c.amount() + " by card";
        case Wallet w -> w.walletId() + " paid " + w.amount() + " by wallet";
        case Cash c -> "Counter received " + c.amount() + " in cash";
    };
}
Emma Clarke paid 250.0 by card
liam.w@wallet paid 80.0 by wallet
Counter received 40.0 in cash

The switch picks a case by the type of p. case Card c means "if it's a Card, call it c" (more in pattern matching). There's no default: javac matches each permitted type to a case and finds all three covered. Add Voucher to the permits list but not the switch, and javac says the switch expression does not cover all possible input values. It points at every switch that hasn't caught up.

Recap

You writeCompiles?
class Oval implements Shape (not permitted)no
class Ring extends Circle (Circle is final)no
class Box extends Square (Square is a record)no
final class Triangle extends Polygon (Polygon permits Triangle)yes
class Star extends Custom (Custom is non-sealed)yes

Close the family with sealed and permits, let each subtype pick final, sealed or non-sealed, and a switch over the records needs no default.

Keep going in Java · 42 of 79

Previous
Java Records: A Whole Data Class in One Line
Next post
Java Pattern Matching with instanceof and switch
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • An interface is open to anyone
  • Sealed classes too
  • Model the real cases
  • A switch with no default
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.