Most developers get this wrong. Do you? 🛑 Early in my Java journey, I thought inheritance was a feature to use freely. The more you extended, the more reusable the code, right? Wrong. Uncontrolled inheritance creates hierarchies nobody can reason about. And Java had no clean answer for it — until sealed classes. ━━━━━━━━━━━━━━━━━━━━━━━━━ Sealed Classes, introduced in Java 17, let you define exactly which classes are permitted to extend yours. No surprises. No rogue subclasses. Just clean, intentional design. public sealed class Shape permits Circle, Rectangle, Triangle {} Each permitted subclass must be one of: → final — no further extension → sealed — further restricted with its own permits → non-sealed — open again by choice And the bonus? Exhaustive pattern matching with switch. The compiler knows every possible subtype. You get compile-time safety for free. ━━━━━━━━━━━━━━━━━━━━━━━━━ I’ve written a full breakdown — how sealed classes work, the rules, and real use cases. Read it here 👇 https://lnkd.in/gsN6Dp7j Have you used sealed classes in your projects? I’d love to hear how! #Java #Java17 #Coding #SoftwareDevelopment #TechCommunity #LearningInPublic #SealedClasses #BackendDevelopment #SoftwareEngineering #CleanCode #OOP
Java 17 Sealed Classes for Clean Inheritance
More Relevant Posts
-
Your switch-case multiplied again. Here's the refactoring that kills it. When your type code only affects data - not behavior - you can replace switch-case with a class. Not if-else chains, not pattern matching. A class where each type is an instance that carries its own data. This works in Java, JavaScript, Kotlin, C# - any language with classes. The idea is simple: if price, weight, and label all depend on a type code, why scatter that knowledge across three switch statements? Put it in one place. Let the constructor enforce completeness. Add a new type? Create a new instance. The compiler tells you what's missing. No grep. No "did I forget a case somewhere". (When types also change behavior, you need a different approach. That's the next post, next week.) I walked through the full refactoring with a pizza example. From int constants to enums to smart classes. Link in the first comment. #cleancode #refactoring #softwarecraft #codequality
To view or add a comment, sign in
-
-
𝗟𝗲𝘁'𝘀 𝗱𝗶𝘀𝗰𝘂𝘀𝘀 𝗝𝗘𝗣𝟱𝟮𝟲. 𝗙𝗿𝗼𝗺 𝗦𝘁𝗮𝗯𝗹𝗲𝗩𝗮𝗹𝘂𝗲 𝘁𝗼 𝗟𝗮𝘇𝘆𝗖𝗼𝗻𝘀𝘁𝗮𝗻𝘁: 𝗮 𝗰𝗵𝗮𝗻𝗴𝗲, 𝗮 𝗯𝗶𝗴 𝗶𝗺𝗽𝗿𝗼𝘃𝗲𝗺𝗲𝗻𝘁 𝗶𝗻 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 I really like the new name LazyConstant in JEP 526. LazyConstant is a name that actually shows how we use LazyConstant. That is important. 𝗠𝘆 𝗼𝗯𝘀𝗲𝗿𝘃𝗮𝘁𝗶𝗼𝗻 𝗳𝗿𝗼𝗺 𝗲𝘅𝗽𝗲𝗿𝗶𝗺𝗲𝗻𝘁𝗶𝗻𝗴 𝘄𝗶𝘁𝗵 𝗶𝘁 Before when we made a constant field in a class it was always initialized when the class was loaded. This means that: ● Even if we never use the value ● Even if you're just running a quick test ● If initializing the constant is expensive Our class loading time still takes a hit. I tried this out with a demo using: java -verbose:class DemoApp And I can see how initialization affects the time it takes to load the class. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝘄𝗶𝘁𝗵 𝗟𝗮𝘇𝘆𝗖𝗼𝗻𝘀𝘁𝗮𝗻𝘁? Now the constant LazyConstant: ● Only loads when we actually need it ● Does not slow down the class loading ● Still keeps the guarantee that it will not change The result is that our program starts up more smoothly and quickly. This is especially important for: ● Microservices (where the time it takes to start up matters a lot) ● Applications with a lot of configuration ● Logging or creating objects 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝗶𝘀 𝗮 𝗯𝗶𝗴 𝗱𝗲𝗮𝗹 𝗶𝗻 𝗿𝗲𝗮𝗹 𝗹𝗶𝗳𝗲: Before LazyConstant we could do lazy initialization but: ● It required a lot of code ● We had to be careful with concurrency ● Often used double-checked locking + synchronized ● It was easy to get it wrong 𝘄𝗶𝘁𝗵 𝗟𝗮𝘇𝘆𝗖𝗼𝗻𝘀𝘁𝗮𝗻𝘁? ● We do not need any extra code patterns ● We do not have to worry about concurrency ● Our code is clean and easy to read 𝗪𝗵𝗲𝗿𝗲 𝗜 𝘁𝗵𝗶𝗻𝗸 𝗟𝗮𝘇𝘆𝗖𝗼𝗻𝘀𝘁𝗮𝗻𝘁 𝘄𝗶𝗹𝗹 𝗵𝗮𝘃𝗲 𝘁𝗵𝗲 𝗶𝗺𝗽𝗮𝗰𝘁: ● The part of the JVM that loads classes ● Linking phase performance ● The overall time it takes to start up It is still a preview feature in JDK 26. Lazyconstant feels like one of those features that will quietly improve a lot of real-world systems. JEP 526: https://lnkd.in/gSVBkfQy #java #programming #engineering #jep #jvm
To view or add a comment, sign in
-
-
𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮’𝘀 𝘃𝗮𝗿 Recently, I explored how Java introduced Local Variable Type Inference (var) in Java 10 and how it transformed the way developers write cleaner and more expressive code. Java has traditionally been known for its verbosity. With the introduction of var through Project Amber, the language took a major step toward modern programming practices—balancing conciseness with strong static typing. 𝗪𝗵𝗮𝘁 𝗜 𝗹𝗲𝗮𝗿𝗻𝗲𝗱: • var allows the compiler to infer types from initializers, reducing boilerplate without losing type safety. • It is not a keyword, but a reserved type name, ensuring backward compatibility. • Works only for local variables, not for fields, method parameters, or return types. • The inferred type is always static and compile-time resolved—no runtime overhead. • Powerful in handling non-denotable types, including anonymous classes and intersection types. Must be used carefully: • Avoid when the type is unclear from the initializer • Prefer when the initializer clearly reveals the type (e.g., constructors or factory methods) • Enhances readability only when the initializer clearly conveys the type. 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆: var is not just about writing less code—it’s about writing clearer, more maintainable code when used correctly. The real skill lies in knowing when to use it and when not to. A special thanks to Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. #Java #Programming #SoftwareDevelopment #CleanCode #Java10 #Developers #LearningJourney
To view or add a comment, sign in
-
💡 𝗝𝗮𝘃𝗮/𝐒𝐩𝐫𝐢𝐧𝐠 𝐁𝐨𝐨𝐭 𝗧𝗶𝗽 - 𝗦𝘄𝗶𝘁𝗰𝗵 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 💎 🕯 𝗧𝗿𝗮𝗱𝗶𝘁𝗶𝗼𝗻𝗮𝗹 𝗦𝘄𝗶𝘁𝗰𝗵 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 The traditional switch statement has been part of Java since the beginning. It requires explicit break statements to prevent fall-through, which can lead to bugs if forgotten. Each case must contain statements that execute sequentially, making the code verbose and error-prone. 💡 𝗠𝗼𝗱𝗲𝗿𝗻 𝗦𝘄𝗶𝘁𝗰𝗵 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 Switch expressions were introduced in Java 14 as a more concise and safe alternative. Using the -> syntax, you eliminate the need for break statements and can directly return values. Multiple cases can be grouped with commas, and the compiler enforces exhaustiveness for better safety. ✅ 𝗞𝗲𝘆 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 ◾ No break statements, safer and cleaner code. ◾ Direct value assignment, treat switch as an expression. ◾ Multiple labels with comma separation. ◾ Compiler exhaustiveness checks, fewer runtime errors. 🤔 Which one do you prefer? #java #springboot #programming #softwareengineering #softwaredevelopment
To view or add a comment, sign in
-
-
I just compiled the entire Java roadmap into a single PDF. Basic → Advanced → Expert. 47 topics. 38 pages. Zero fluff. Here's what's inside 👇 ↳ Core syntax, OOP, and collections ↳ Streams, lambdas, and Optional done right ↳ Concurrency — from synchronized to Virtual Threads ↳ JVM internals, GC tuning, and memory management ↳ Pattern matching, records, sealed classes ↳ Project Loom, structured concurrency, and the future of Java Whether you're writing your first "Hello, World" or debugging a GC pause at 3 AM, this guide has something for you. PDF attached. 📩 ♻️ Repost to help another dev level up. #Java #Programming #SoftwareEngineering #BackendDevelopment #LearnToCode #JVM #CodingTips #Developer #SpringBoot #TechCommunity
To view or add a comment, sign in
-
Recently revisited an important Java Streams concept: reduce() - one of the most elegant terminal operations for aggregation. Many developers use loops for summing or combining values, but reduce() brings a functional and expressive approach. Example: List<Integer> nums = List.of(1, 2, 3, 4); int sum = nums.stream() .reduce(0, Integer::sum); What happens internally? reduce() repeatedly combines elements: 0 + 1 = 1 1 + 2 = 3 3 + 3 = 6 6 + 4 = 10 Why it matters: ✔ Cleaner than manual loops ✔ Great for immutable / functional style code ✔ Useful for sum, max, min, product, concatenation, custom aggregation ✔ Common in backend processing pipelines Key Insight: Integer::sum is just a method reference for: (a, b) -> a + b Small concepts like this make code more readable and scalable. Still amazed how much depth Java Streams offer beyond just filter() and map(). #Java #Programming #BackendDevelopment #SpringBoot #JavaStreams #Coding #SoftwareEngineering
To view or add a comment, sign in
-
The most expensive line of code you ever wrote was in Java. It was 2am. The service was down. Your phone vibrating on the nightstand. NullPointerException at line 247. You trace it back. The method returned null instead of a value. The exception you didn't catch bubbled up silently. You'd shipped this 3 weeks ago. It had been waiting for exactly the right conditions to break. You fixed it. You moved on. You called it normal. That's the part that should bother you. You called it normal. In Rust, that code doesn't compile. The compiler catches it before you run it — before you test it, before you ship it, before the 2am call. "This can be null. Handle it." "This can fail. Handle it." "This value could be missing. Handle it." Every edge case you've ever debugged at midnight — Rust surfaces it before you hit Save. One language lets you ship the question. The other makes you answer it first. Follow me. #java #rust #programming
To view or add a comment, sign in
-
-
Day 83 - LeetCode Journey Solved LeetCode 237: Delete Node in a Linked List in Java ✅ This problem was a bit different from usual linked list questions. Instead of deleting a node in the traditional way, we weren’t given access to the head of the list. That’s what made it interesting. The trick was to think differently. Instead of removing the node directly, copy the value of the next node into the current node and skip the next node. Simple idea, but not obvious at first. This problem really tests your understanding of how linked lists work internally. Key takeaways: • Thinking beyond standard approaches • Understanding pointer manipulation deeply • Writing minimal and efficient code • Strengthening core linked list concepts ✅ All test cases passed ✅ Clean and optimal solution Problems like these remind me that DSA is not just about coding, but about thinking differently 💡 #LeetCode #DSA #Java #LinkedList #ProblemSolving #Algorithms #CodingJourney #InterviewPreparation #Consistency
To view or add a comment, sign in
-
-
CSBytes #58 - The difference between a tightly coupled application and a loosely coupled, maintainable one is understanding Dependency Injection (DI). When you switch from plain #Java to #SpringBoot, DI changes everything. But how? In my latest article, I explain: The absolute simplest way to think about DI. The practical difference between manual coding and Spring's auto-magic (IoC). Why this matters for clean, testable code. Perfect for anyone needing a simpler way to explain #SoftwareDesign. Link: [https://lnkd.in/gii6p6wY] #Java #SpringBoot #SoftwareDevelopment #CodingTips #TechConcepts
To view or add a comment, sign in
-
I almost overcomplicated this problem… until I realized it was just prefix sum. 👉 Equal Sum Grid Partition (LeetCode 3546) At first, I thought: “Try all possible cuts.” But that quickly gets messy. Then the real insight hit: If the total sum is even, we just need to find a prefix (row-wise or column-wise) equal to total / 2. That’s it. No brute force. Just clarity. 💡 Lesson: The problem is not about splitting the grid — it’s about finding the right prefix. Time: O(m × n) Space: O(n) Sharing the clean Java solution on GitHub 👇 #leetcode #dsa #java #coding #developers #softwareengineer #codewithishwar
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