Intermediate 18 min readModule: Module 6: Interfaces, Records & Sealed Classes
Interfaces, Default Methods & Sealed Classes
Implement multiple interfaces, declare immutable Records, and restrict subclassing with 'sealed'.
What You Will Learn in This Lesson
- Multiple interface implementation (implements A, B)
- Default method implementations in interfaces
- Sealed classes (sealed class Shape permits Circle, Square) for exhaustive pattern matching
Introduction & Core Concept
Interfaces define behavioral contracts. Sealed classes allow authors to explicitly declare which classes are permitted to extend them, enabling compiler-enforced exhaustiveness.
WHY DOES THIS MATTER IN THE REAL WORLD?
Sealed classes prevent third-party code from extending internal domain models in unexpected ways.
Sealed Class Hierarchy
javajava
1234567public sealed interface Result permits Success, Failure {}public record Success(String data) implements Result {}public record Failure(String error) implements Result {}// Pattern matching in Java 21// switch (result) { case Success s -> ... case Failure f -> ... }
Line-by-Line Technical Breakdown
1Interfaces can have static methods and private helper methods as well as default methods.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[JAVA]
JAVA SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Use sealed interfaces to model algebraic data types (ADTs) in Java.
Lesson Summary & Core Takeaways
- Interfaces and sealed classes provide total control over class contracts and hierarchies.