Java Sealed Classes: Control Inheritance with Java 17

🚀 #Day61 of My Java Learning! Today, I explored 𝐒𝐞𝐚𝐥𝐞𝐝 𝐂𝐥𝐚𝐬𝐬𝐞𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚 and understood how Java gives us more control over inheritance. 📘 𝐖𝐡𝐚𝐭 𝐚𝐫𝐞 𝐒𝐞𝐚𝐥𝐞𝐝 𝐂𝐥𝐚𝐬𝐬𝐞𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚? ➜ Sealed classes allow us to restrict which classes can extend or implement them ➜ The parent class explicitly declares the permitted subclasses ➜ Helps in designing controlled and predictable class hierarchies ✨ 𝐈𝐧𝐭𝐫𝐨𝐝𝐮𝐜𝐭𝐢𝐨𝐧 𝐃𝐞𝐭𝐚𝐢𝐥𝐬 • Feature Type: Predefined language feature • Introduced in: Java 15 (preview), stabilized in Java 17 • Package: java.lang (language-level feature, no explicit import needed) 📌 𝐖𝐡𝐲 𝐒𝐞𝐚𝐥𝐞𝐝 𝐂𝐥𝐚𝐬𝐬𝐞𝐬 𝐚𝐫𝐞 𝐔𝐬𝐞𝐟𝐮𝐥? ➜ Prevents unintended subclassing ➜ Improves code safety and maintainability ➜ Makes domain models more clear and expressive ➜ Very helpful in frameworks, APIs, and business rules ➜ Works well with pattern matching and switch expressions ✨ 𝐑𝐮𝐥𝐞𝐬 𝐢𝐧 𝐒𝐞𝐚𝐥𝐞𝐝 𝐂𝐥𝐚𝐬𝐬𝐞𝐬 • A sealed class must use the permits keyword • Permitted subclasses must be one of the following: – final → cannot be extended further – sealed → can further restrict subclasses – non-sealed → open for extension ✨ 𝐖𝐡𝐚𝐭 𝐈 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐞𝐝 𝐓𝐨𝐝𝐚𝐲 ➜ Created a sealed parent class using permits ➜ Implemented: – a final subclass – a sealed subclass – a non-sealed subclass ➜ Observed how inheritance is strictly controlled ➜ Executed methods from parent class across all permitted subclasses 💡 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 🔹 Sealed classes bring better design control 🔹 Java now supports restricted inheritance natively 🔹 Makes large applications more robust and readable 10000 Coders | Gurugubelli Vijaya Kumar #Java #CoreJava #SealedClasses #Java17 #OOP #LearningJava #100DaysOfCode #JavaDeveloper

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories