As a developer if you want to control who can extend your class or interface.
In this enhancement of Java programming language, new keywords are introduced sealed, non-sealed and permit at the class level.
A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so. If you try to implement or extend to other class which is not permitted then the code will not compile. For example,
public sealed class Point permits Line
A permit keyword defines which are the subclasses or interfaces can be extended or implemented from this class. For example,
public sealed class Point permits Line
Point class only permits Line class to extend directly.
A non-sealed class or interface will allow this class to be extended.
For example,
public non-sealed class Line
Permitted class Line is open for any unknown class extension.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class Shape permits Circle { | |
public void name() { | |
System.out.println("This is Shape."); | |
} | |
public static void main(String args[]) { | |
Shape shape = new Shape(); | |
shape.name(); | |
Shape newShape = new Circle(); | |
newShape.name(); | |
} | |
} | |
non-sealed class Circle extends Shape { | |
@Override | |
public void name() { | |
System.out.println("This is Circle."); | |
} | |
} | |