Java 17 Sealed Classes Explained

🔒 Sealed Classes in Java — Explained Simply #️⃣ Sealed Classes Introduced in Java 17, sealed classes give developers controlled inheritance. 🔹 What is a Sealed Class? A sealed class restricts which classes can extend or implement it. 👉 Only explicitly permitted classes are allowed to inherit. Think of it as: 🔒 Inheritance with security and control 🧩 Example public sealed class Shape permits Circle, Rectangle {} final class Circle extends Shape {} final class Rectangle extends Shape {} Here: ✔ Only Circle and Rectangle can extend Shape ❌ No other class is allowed to extend it 🔹 Why were Sealed Classes introduced? Before sealed classes: ⚠ Anyone could extend your class ⚠ You had no control over inheritance ⚠ API design became unpredictable ⚠ Security risks increased Sealed classes solve this by: ✅ Controlling hierarchy ✅ Improving maintainability ✅ Enforcing design rules ✅ Supporting safe polymorphism 🔹 Rules of Sealed Classes Every permitted subclass must be: ✔ final → cannot extend further ✔ sealed → can restrict again ✔ non-sealed → opens inheritance Example: public sealed class Vehicle permits Car, Bike {} final class Car extends Vehicle {} non-sealed class Bike extends Vehicle {} 👉 Bike allows further inheritance 👉 Car does not 🔹 When should we use Sealed Classes? Use sealed classes when: ✔ You want controlled inheritance ✔ Designing frameworks/APIs ✔ Modeling fixed domain hierarchies ✔ Creating safe polymorphic systems ✔ Building DSLs or state machines 🔹 Real-world Use Cases 🚗 Vehicle systems 💳 Payment states 🎮 Game character hierarchy 🏦 Banking transaction types 📦 Order status modeling Anywhere the hierarchy is fixed and predictable. 🎯 Interview Tip If interviewer asks: Why sealed classes instead of final classes? Answer: 👉 Final class prevents inheritance entirely 👉 Sealed class allows inheritance — but controlled It balances flexibility + safety. 🏁 Key Takeaways ✔ Sealed classes restrict inheritance ✔ Introduced in Java 17 ✔ Improves API design ✔ Supports safe polymorphism ✔ Controls class hierarchy ✔ Enhances maintainability #Java #Java17 #SealedClasses #ModernJava #JavaFeatures #BackendDevelopment #ProgrammingConcepts #JavaDeepDive #TechWithVijay #VFN #vijayfullstacknews

To view or add a comment, sign in

Explore content categories