🔒 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
Java 17 Sealed Classes Explained
More Relevant Posts
-
🚫 Preventing Inheritance in Java — 3 Practical Techniques Every Developer Should Know Inheritance is powerful, but not every class is meant to be extended. Java gives us multiple ways to intentionally stop inheritance and protect design integrity. 1️⃣ final Keyword Marking a class as final prevents any other class from extending it. code :- final class UtilityClass { // methods } ✅ Used when behavior should remain unchanged 📌 Example: String, Integer 2️⃣ Private Constructor A class with a private constructor cannot be instantiated or extended outside the class. code :- class Constants { private Constants() {} } ✅ Common in utility classes and singleton patterns 📌 Prevents both inheritance and object creation 3️⃣ sealed Classes (Java 17+) sealed classes allow inheritance — but only by specific, permitted classes. code:- public sealed class Shape permits Circle, Rectangle {} Copy code Java final class Circle extends Shape {} final class Rectangle extends Shape {} ✅ Fine-grained control over class hierarchies 📌 Great for domain modeling and pattern matching 🔍 When should you prevent inheritance? ✔ To enforce immutability ✔ To protect business rules ✔ To avoid misuse of base classes ✔ To maintain clean architecture 💡 Good design isn’t about allowing everything — it’s about allowing the right things. #Java #OOP #SystemDesign #CleanCode #SoftwareEngineering #JavaDeveloper #BackendDevelopment
To view or add a comment, sign in
-
🧱Blocks — The Execution Order One common Java interview question: When Parent and Child classes both have static blocks, instance blocks, and constructors — what runs first? Few understand why. 🧠 First Principle: How Java Builds an Object When creating a Child object, Java does not build the child first. It builds the Parent part first, then completes the Child. Object creation always happens top → down in the inheritance chain. ⚙️ Step 1: Class Loading Phase (Runs Only Once) Static blocks belong to the class, not the object. They execute when the class is loaded into memory. Execution Order 1️⃣ Parent static block 2️⃣ Child static block No matter how many objects you create later → static blocks won’t run again. 🏗 Step 2: Object Creation Phase (Runs Every Object Creation) For each class in inheritance: ➡️ Instance Block ➡️ Constructor So full execution becomes: Parent static Child static Parent instance block Parent constructor Child instance block Child constructor 🎯 Why This Happens Because a Child object literally contains a Parent inside it. Java must construct the Parent portion first before finishing the Child portion. 📌 Where Blocks Are Used Static blocks • Loading drivers • Initializing configuration • Creating caches • One-time setup logic Instance blocks • Shared constructor logic (rare; constructors preferred) GitHub Link: https://lnkd.in/gj6uhVv3 🔖Frontlines EduTech (FLM) #JAVA #corejava #blocks #BackendDevelopment #Programming #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #instance #static #constructor
To view or add a comment, sign in
-
-
🚀 Day 17 – Core Java | Classes, Objects & Coding Conventions Today’s session was about strengthening the foundation of Object-Oriented Programming before moving to arrays. We didn’t jump to a new topic. We reinforced what truly matters. 🔑 What We Covered ✔ Classes & Objects – Practical Implementation We created a Car class with: Instance Variables → name, cost, mileage Methods → start(), accelerate(), stop() Then we created multiple objects and traced how memory behaves. 🧠 Memory Understanding (Very Important) When object is created: Stack → Holds reference variables Heap → Stores actual object Each object has separate memory Two objects of same class: Have same blueprint But different memory locations No shared data unless explicitly referenced This clarity prevents confusion between: Object creation Reference variables Pass by value Pass by reference ✔ Method Execution Flow When calling: c.start(); Stack frame of main exists New stack frame of start() is pushed Executes Pops after completion Understanding stack frames = Understanding Java execution. ✔ Static vs Non-Static Clarification We saw why: main() is static Non-static methods cannot be directly accessed inside static context Object creation is required This confusion is common in interviews. Now it’s clear. ✔ Coding Conventions (Professional Practice) We learned industry-level naming standards: 🔹 Class Name → PascalCase Example: CarDetails 🔹 Method & Variable Name → camelCase Example: calculateTotal() These conventions don’t affect compilation — But they define professionalism. ✔ Built-in vs User-Defined User-defined: Your own classes Your own methods Built-in: Scanner String Exception Thread StringBuilder (and thousands more) We also learned: Ctrl + Shift + O → Auto import in Eclipse 💡 Biggest Takeaway 70% of Java foundation is already built: Data types Variables Methods Classes Objects Execution flow Everything upcoming (Arrays, Strings, OOP concepts, Advanced Java) depends on this base. If stack & heap are clear → Java becomes easy. If not → Every future topic feels difficult. Strong foundation today = Strong developer tomorrow. #Day17 #CoreJava #ObjectOrientedProgramming #JavaExecution #StackAndHeap #CodingStandards #JavaDeveloper #LearningJourney
To view or add a comment, sign in
-
Day 4 | Full Stack Development with Java Today I explored one of the most important concepts in Java — the Main Method and how execution actually begins inside a program. What I learned today: Control of Execution In Java, execution always starts from the main() method. Even if multiple functions exist, none will run unless the main method gives control. The JVM looks for a specific signature to start execution. Why public static void main(String[] args)? public → Makes the method visible to JVM. static → Allows execution without creating an object. void → No return value. String[] args → Stores command-line inputs as an array. Command Line Arguments (args) args collects data passed during program execution. It acts like a dynamic array that stores runtime inputs. Helps make programs flexible and dynamic. Object Creation Reminder Objects are created using the new keyword. Steps include declaration, instantiation, and initialization. Key Takeaway Understanding how the main method controls execution helped me realize how Java programs actually start running behind the scenes. Strong fundamentals are making advanced backend concepts easier to understand. #Day4 #Java #MainMethod #FullStackDevelopment #LearningInPublic #SoftwareDevelopment
To view or add a comment, sign in
-
-
Day 6 of Java: From Actions to Architecture 🏗️ One week in, and the pieces are starting to form a bigger picture. If Day 5 was about "how things work" (Methods), Day 6 was about "how things are built." To keep the complexity simple, I’ve broken today's breakthroughs down into three more real-world metaphors: 1. Arrays: The "Egg Carton" Principle 🥚 As my programs grow, I can’t just have loose variables rolling around. Enter the Array. The Concept: Think of an egg carton. It has a fixed size (12 slots) and can only hold one type of thing (eggs). The Rule: In Java, once you define the size of an Array, it’s set. You can’t turn a 6-slot carton into a 12-slot one mid-way through. It teaches you to plan your "storage" before you start the heavy lifting. 2. Classes vs. Objects: The "Blueprint vs. House" 🏠 This is the heart of Object-Oriented Programming (OOP), and it’s a total game-changer. The Class (The Blueprint): This is the paper drawing of a house. It defines where the windows go and how many rooms there are, but you can't live in a drawing. The Object (The House): This is the actual physical building created from that blueprint. I can use one blueprint (Class) to build ten different houses (Objects), each with its own paint color or address, but the structure remains the same. 3. Constructors: The "Factory Settings" ⚙️ When you buy a new phone, it comes with certain things already set up (language, brightness, default apps). In Java, that’s a Constructor. The Function: It’s a special "starter" method that runs the moment an Object is created. Why it matters: It ensures that every "House" I build isn't empty—it comes with the doors locked and the lights off by default. Progress Report: Moving from writing "scripts" to designing "systems" feels like a major level-up. The syntax is becoming the tool, while the logic is becoming the craft. On to Day 7! 🚀 #Java #ObjectOrientedProgramming #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
I recently revisited Chapter 4: "Classes and Interfaces" in Joshua Bloch's book Effective Java (3rd edition). Here are the key takeaways I found most valuable: 1. Class Design Principles • Minimize accessibility: make classes and members as private or package- private as possible. • Favor immutability: immutable objects are simpler, safer, and easier to reason about. • Prefer composition over inheritance: use delegation unless there is a clear “is-a” relationship. 2. Interfaces vs Abstract Classes • Interfaces define behavior; abstract classes can provide partial implementation. • Use interfaces to specify contracts and allow multiple inheritance of behavior. • Abstract classes are useful for sharing code among subclasses. 3. Designing for Inheritance • Classes should be designed either for inheritance or made final. • Carefully document methods intended for overriding to prevent misuse. 4. Nested & Static Member Classes • Static nested classes are preferred when the outer class instance is not needed. • They improve encapsulation and reduce memory leaks. 💡 My takeaway: Good class and interface design is about clarity, maintainability, and flexibility. Thinking ahead about immutability, accessibility, and proper use of inheritance makes your Java code more robust and future-proof. #Java #Classes #Interfaces #EffectiveJava #CleanCode #SoftwareEngineering #JavaTips #Coding #JavaDevelopment
To view or add a comment, sign in
-
Deep Dive into Abstraction in Core Java Just implemented and explored one of the core pillars of Java OOP — Abstraction! In my project, I used an abstract class House to define what a house should do (like pillars() and walls()), while letting each subtype decide how it does it. 📁 Code link: https://lnkd.in/gbez5BHU 🧠 What I learned: 🔹 Abstraction helps define essential behavior without implementation details 🔹 Abstract classes allow shared concrete methods (basement(), windows()) 🔹 Runtime polymorphism enables switching behavior dynamically 🔹 Clean design and reusable code The classes I worked with: WoodHouse GlassHouse ConcreteHouse —all extending the abstract House class with their specific implementations ✨ 💡 Abstraction isn’t about hiding complexity — it’s about focusing on what matters most in object design. Huge thanks to my mentor Anand Kumar Buddarapu for guiding me through strong OOP foundations. Continuing the Java journey — step by step, concept by concept. 💻🔥 #Java #CoreJava #Abstraction #OOP #Polymorphism #CleanCode #GitHub #LearningByDoing #SoftwareEngineering
To view or add a comment, sign in
-
🔍 Understanding SOLID Principles in Java – A Quick Overview 🚀 Want to write cleaner, more maintainable, and scalable Java code? Start with the SOLID principles — five foundational guidelines that help you build better object-oriented software: ✨ S – Single Responsibility Principle A class should have only one reason to change. 🔗 O – Open/Closed Principle Software entities should be open for extension but closed for modification. 🔄 L – Liskov Substitution Principle Objects of a superclass should be replaceable with objects of a subclass without breaking the application. 🔗 I – Interface Segregation Principle Clients should not be forced to depend on interfaces they do not use. 🧩 D – Dependency Inversion Principle High-level modules should not depend on low-level modules — both should depend on abstractions. 📌 These principles improve design quality and help avoid tightly coupled code. Learn more with simple explanations and examples on GitHub: 👉https://lnkd.in/gftuUKCq ✨ Follow the link for easy-to-understand notes and dive deeper into SOLID! #Java #SOLID #SoftwareDesign #CleanCode #GitHub
To view or add a comment, sign in
-
-
🚀 Day 3 of My 90 Days Java Full Stack Challenge Today I practiced core OOP concepts in Java through hands-on design problems instead of just theory. Here’s what I worked on: 🔹 Encapsulation + Constructors → Built a Bank Account system with validation and controlled data access 🔹 Access Modifiers in Inheritance → Understood how private, protected, and public behave in parent-child classes 🔹 Constructor Chaining → Learned how super() and this() control object initialization order 🔹 Runtime Polymorphism → Used method overriding with parent references and child objects 🔹 Composition vs Inheritance → Modeled real-world HAS-A relationships instead of misusing inheritance 🔹 Abstraction → Created a Shape system using abstract classes and method overriding Big realization: OOP is not about memorizing definitions — it’s about designing classes the way real-world systems behave. Slowly turning theory into practical design thinking 💻 #90DaysChallenge #Java #OOPS #LearningInPublic #DeveloperJourney #FullStackDeveloper
To view or add a comment, sign in
-
🧵 Mastering Thread Lifecycle & State Transitions in Java 🚀 Understanding thread states is crucial for writing efficient, bug-free concurrent applications. Here's a quick breakdown: 6 Thread States in Java: 1️⃣ NEW – Thread created but not started 2️⃣ RUNNABLE – Executing or ready to execute 3️⃣ BLOCKED – Waiting for monitor lock 4️⃣ WAITING – Waiting indefinitely for another thread 5️⃣ TIMED_WAITING – Waiting for a specified time 6️⃣ TERMINATED – Execution completed Key Transitions: • start() → NEW → RUNNABLE • sleep()/wait(timeout) → RUNNABLE → TIMED_WAITING • wait() → RUNNABLE → WAITING • I/O or lock acquisition → RUNNABLE → BLOCKED • notify()/notifyAll() → WAITING → RUNNABLE Q1: What's the difference between BLOCKED and WAITING states? A: BLOCKED occurs when a thread is waiting to acquire a monitor lock. WAITING happens when a thread waits indefinitely for another thread to perform a specific action (like notify() or join()). BLOCKED is lock-specific, WAITING is action-specific. Q2: Can a thread transition directly from WAITING to RUNNABLE without entering BLOCKED? A: Yes! When notify()/notifyAll() is called, the waiting thread moves directly to RUNNABLE state. It only enters BLOCKED if it needs to reacquire a lock that's held by another thread. Q3: How does yield() affect thread state? A: yield() is a hint to the scheduler that current thread is willing to pause its execution. The thread remains in RUNNABLE state and may immediately resume running—no state change occurs. It's just a suggestion, not guaranteed behavior. 💡 Pro Tip: Use jstack or visualvm to monitor thread states in production applications—invaluable for debugging deadlocks and performance issues! What threading challenges have you faced recently? 👇 #Java #Multithreading #Concurrency #Programming #SoftwareEngineering
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development