
- In Java, inheritance allows you to inherit the fields, methods, and nested classes of the parent class, and also add new features through polymorphism and method overriding.
- Declaring a class as final , prevents the class from getting inherited or extended.
- So at one end of the spectrum we have inheritance, which allows any subclass to extend a class, and at the other end, we have final, which doesn’t allow any subclass to extend it.
- There is nothing in between that allows a class to be extended or inherited by only a certain number of classes. Inheritance is an all-or-nothing kind of thing in Java
- The release of Java SE 17 introduces sealed classes (JEP 409). Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them
- The Sealed class enables developers to precisely specify which subclasses are permitted to extend the super class.
- A sealed class declares a list of classes that can extend it, while the subclasses declare that they extend the sealed class
- The aim of this feature is to let you control the hierarchies of your class by declaring , which specific classes can extend your class.
- Programmers can declare a Sealed class with the keyword sealed. Then we provide the class name and use the permit clause to specify allowable subclasses. Note that both the keywords, sealed and permits, are context-sensitive and have a special meaning in relation to class or interface declaration
- Declaration of a Sealed Class
public sealed class Fruits permits Oranges,Apple {
...
}
- In this example, the class Fruits is inheritable by class Oranges and Apple; no other class can inherit it.
- Below code will not be allowed and will throw an error
public final class Spinach extends Fruits { } // Error! Spinach cannot extend Fruits
- A subclass of a sealed class must be declared as final, sealed, or non-sealed.
- When permitted class is declared final, it means that the permitted subclasses are not further inheritable
- When permitted class is declared sealed, it means that the permitted subclass can be further extended.
- When permitted class is declared non-sealed, It can be extended by any subclasses. It kind of lets you bypass the sealed property or conditions via its own subclass
- Sealed interfaces are declared in much the same way as Sealed classes. Here, the permit clause is used to specify which class or interface is allowed to implement or extend the Sealed interface
With sealed class now we can enforce extension of classes that is known in compile time.
Thank You !!