Issue
Suppose there is class A
which is parent class and class B
that extends A
.
Now I should not allow to extend class A
to class C
(class C extends A
), or any other class.
How to do that?
Solution
That's why Java 17 has sealed classes. This feature was added as a preview feature in Java 15.
In your case you can do the following:-
public sealed class A permits B {
}
public class B extends A{ //No error
}
public class C extends A{ //error because class C is not permitted
}
The Goals of Sealed classes in java are :-
Allow the author of a class or interface to control which code is responsible for implementing it.
Provide a more declarative way than access modifiers to restrict the use of a superclass.
Support future directions in pattern matching by providing a foundation for the exhaustive analysis of patterns.
IF you want a class not extendable, then you can use final
.
public final class A{ //Cannot be extended by other classes.
}
Helpful links:
https://docs.oracle.com/en/java/javase/15/language/sealed-classes-and-interfaces.html
http://openjdk.java.net/jeps/409
https://www.baeldung.com/java-sealed-classes-interfaces
What are sealed classes in Java 17
Answered By - JFan