Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet39/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   35   36   37   38   39   40   41   42   ...   245
Bog'liq
Java 17 Recipes

2-9. Sealed Classes
 Problem
You want to create a class or interface and decide which modifier should be used simply.
 Solution
Java 17 finalizes the sealed scope modifier for classes and interfaces.
In the following example, the LineShape class permits exactly and only three 
subclasses: Rectangle, Triangle, and Square.
public sealed class LineShape permits Rectangle, Triangle, Square {}
In the following example, the Rectangle class is declared as final. Thus no other 
classes can extend this class.
public final class Rectangle extends LineShape {}
In the following example, the Triangle class is declared non-sealed, opening an 
extension for unknown classes.
public non-sealed class Triangle extends LineShape {}
Finally,
public sealed class Square extends LineShape permits ColorSquare {}
where the Square class permits exactly and only ColorSquare:
public final class ColorSquare extends Square {}
Chapter 2 enhanCements from Java 9 through Java 17 


63
 How It Works
This enhancement was proposed in Java 15 and finalized in Java 17 (JEP 409) with 
no changes from the last version. The sealed scope modifier allows controlling the 
permitted subtypes for classes and interfaces. A class can also be non-sealed (i.e., it can 
be extended by any unknown subclasses).
A sealed class sets three constraints on its permitted subclasses (i.e., the Rectangle 
and Triangle subclasses) must belong to the same module as the sealed class, they 
must extend the sealed class (Rectangle extends LineShape and public non-sealed class 
Triangle extends LineShape). The subclass must define a modifier: final, sealed, or 
non-sealed.
To compile LineShape.java, the compiler must access all the permitted classes of 
Shape: Triangle.java, Square.java, and Rectangle.java. In addition, because Square 
is a sealed class, the compiler also needs access to ColorSquare.java. Moreover, if 
an “invalid” class tries to extend LineShape, as shown in the following example, the 
compiler gives a warning: “The type Rhombus extending a sealed class LineShape 
should be a permitted subtype of LineShape.”
public final class Rhombus extends LineShape {}
This feature introduces three new keywords in the Java language: sealed, permits, 
and non-sealed.
For more information on sealed classes, see the documentation at 
https://
openjdk.java.net/jeps/409
.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   35   36   37   38   39   40   41   42   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling