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!