☕
Core Java Roadmap Phase 09
0 / 40 (0%)
☰ Syllabus Index Next: P10 →

Java 17 LTS (with 12-16) • Sealed Classes, Records, Pattern Matching & Switch Expressions

📂 Repository Module: Module 2_ Java LTS Features \ 01_Java17_Demos
📖 Textbook Alignment: Volume I — Chapter 4: Objects and Classes (Records) • Chapter 5: Inheritance (Sealed Classes & Pattern Matching)
Phase 9

Java 17 LTS (with 12-16) • Sealed Classes, Records, Pattern Matching & Switch Expressions

📂 Module 2_ Java LTS Features \ 01_Java17_Demos
📖 Core Java Textbook Alignment: Cay S. Horstmann • Volume I — Chapter 4: Objects and Classes (Records) • Chapter 5: Inheritance (Sealed Classes & Pattern Matching)

9.1 Sealed Classes & Interfaces (permits) and Java 16 Records

📖 Cay S. Horstmann • Core Java Volume I — Chapter 5, Section 5.3 ("Sealed Classes")
“Sealed classes give you control over which classes can inherit from your class. When you declare a class as sealed, you must list all permitted subclasses with the permits keyword. Every permitted subclass must declare whether it is final, sealed, or non-sealed. This allows the compiler to know the exhaustive set of all possible subclasses, enabling comprehensive compile-time checks in switch statements without requiring a default branch.”
  • Permitted Subclass Rule Three Required Modifiers: Every subclass of a sealed class must explicitly declare itself as: final (no further subclasses), sealed (permits its own specific hierarchy), or non-sealed (re-opens hierarchy to arbitrary extension).
  • Java 16 Records Transparent Immutable Data Carriers: record Point(int x, int y) {} automatically generates final fields, canonical constructor, accessors, equals(), hashCode(), and toString() in 1 line of code!
💡 Real-World Analogy: The Exclusive VIP Club with Guest List
• Regular Class: An open public park. Anyone can show up and build a tent (subclass) anywhere. You cannot anticipate who will arrive tomorrow.
• Sealed Class: An exclusive VIP event with a security guard checking a strict printed guest list (permits Electronics, Beauty, Kids). If an unauthorized class (e.g. HomeAppliances) tries to enter, the compiler security denies entry immediately!
📂 Module 2_ Java LTS Features/.../Product.java & Tester1001Sealed.java
package com.accenture.ltt.sampleclasses;

// 1. Sealed Superclass: Only permitted subclasses may extend it!
public sealed abstract class Product 
    permits ElectronicsProducts, KidsProducts, BeautyProducts {
    
    public abstract String getProductDescription();
}

// Subclass 1: final prevents any further subclassing
public final class ElectronicsProducts extends Product {
    @Override
    public String getProductDescription() { return "Consumer Electronics & Gadgets"; }
}

// Subclass 2: non-sealed re-opens class for open subclassing
public non-sealed class BeautyProducts extends Product {
    @Override
    public String getProductDescription() { return "Cosmetics and Skincare"; }
}

// Subclass 3: final
public final class KidsProducts extends Product {
    @Override
    public String getProductDescription() { return "Toys & Apparel for Children"; }
}

/* Attempting to define an unauthorized subclass results in:
class HomeAppliances extends Product {} // COMPILATION ERROR: class is not allowed to extend sealed class */
⚡ Pro-Tip / Interview Memory Hook: Exhaustive Switch with Sealed Hierarchies
No default branch required! When you switch over a sealed interface or class and provide a case for every single permitted subtype, the compiler knows all possibilities. You do not need a default clause! If someone later adds a new permitted subclass, the compiler alerts you at compile time wherever the switch is incomplete.
👁 Execution & Memory Breakdown • Sealed Classes & Pattern Matching
Step 1 (Permitted Subclasses): The JVM ClassLoader stores permitted subclasses in a PermittedSubclasses bytecode attribute; any non-listed class attempting inheritance causes an IncompatibleClassChangeError during verification.
Step 2 (Pattern Matching): The compiler checks the type and binds the target local variable in a single bytecode sequence, eliminating unnecessary casting opcodes.

9.2 Pattern Matching for instanceof, Switch Expressions & Text Blocks

📖 Cay S. Horstmann • Core Java Volume I — Chapter 3 & Chapter 5 ("Pattern Matching & Switch Expressions")
“Java 17 enhances pattern matching to eliminate the tedious dance of testing with instanceof and then explicitly casting. With pattern matching, the target variable is automatically bound in the branch where the test succeeds. Combined with switch expressions that yield values and arrow syntax (->) that prevents fall-through bugs, Java provides modern expressive syntax comparable to modern functional languages.”
📂 Module 2_ Java LTS Features/.../PatternSwitchDemo.java
package com.accenture.ltt.ui.tester.java17;

public class PatternSwitchDemo {
    public static void main(String[] args) {
        Object obj = "Java 17 LTS";

        // 1. Pattern Matching in Switch Expression (No break required! Arrow syntax)
        String result = switch (obj) {
            case String s -> "String of length " + s.length() + ": " + s.toUpperCase();
            case Integer i -> "Calculated integer: " + (i * 2);
            case Double d -> "Double precision: " + String.format("%.2f", d);
            default -> "Unknown type object";
        };
        System.out.println(result);

        // 2. Multi-line Text Blocks (Java 15) with automatic indentation stripping
        String jsonPayload = """
            {
                "framework": "Core Java 17 LTS",
                "status": "Production Ready",
                "security": "Enforced"
            }
            """;
        System.out.println("Text Block JSON:
" + jsonPayload);
    }
}