Why do we need a Sealed Class?

Why do we need a Sealed Class?

Hello Folks,

In the last article here, we discussed about what is exactly the concept of Sealed? Today, we are going to dig one step ahead as WHY actually do we need such a concept?

This concept was added to Java as a *preview feature with JDK15, and now it's been officially incorporated with JDK17.

Coming back to Why?

As it's related to inheritance, so few words about it first. One of the primary goals of inheritance is code reuse meaning you want to reuse the functionality already existing in the super class instead of rewriting it in the sub class.

If I ask you, is there a way to restrict the inheritance of a class? The answer is YES. Simply, we can make a class final, e.g. String is a final class, which means no other class can extend it. Therefore, we have two choices - either we have a class final means no one can extend it or we have a non-final class means everybody can extend it.

So, where does sealed class concept come? It sits in between the two conditions we just talked about.

We want to give control in the hands of the author of class to decide who all can extend it (or in case of interface, who all can implement it) Meaning, if you're writing a library code which you want to expose to other members keeping the control with you who can extend your exposed functionality, that's where 'sealed' comes to your help. Would like to introduce a technical term here - This is what 'Secured Hierarchy' means.

I hope I was able to explain the why part to you.

Would like to end by an example - e.g. If you create a class named Shape for which you want only Circle or Rectangle can be the possible shapes. You can seal the Shape class.

Next, we would discuss about How can we actually do that? Interested in learning? Stay tuned !

Thanks for reading this far!

要查看或添加评论,请登录

Shiv Dhiman的更多文章

  • Team Fridays | Decision-making activity around Conflicting views

    Team Fridays | Decision-making activity around Conflicting views

    This Friday's session with the team was around a decision-making activity around conflicting views on a problem…

  • Team Fridays | Learning & Sharing

    Team Fridays | Learning & Sharing

    Learning and sharing are key to the team's cohesiveness and growth. And, Fridays, I believe, are the best days to do so.

  • How to write a Sealed Interface ?

    How to write a Sealed Interface ?

    Finally, we've come to the last part of the Sealed concept. We've already learnt - what, why and how parts in last…

  • How to write a Sealed Class ?

    How to write a Sealed Class ?

    In the last two articles, we discussed the what and why parts - as what's a sealed class and second, why do we even…

  • What is a Sealed Class/Interface ?

    What is a Sealed Class/Interface ?

    Hello Folks, Java version 17 has been released around 15 days ago in Sept, 2021. There are a number of features that…

社区洞察

其他会员也浏览了