JDK 15 Sealed 类 - 如何跨包使用?
JDK 15 Sealed Classes - how to use across packages?
我有一个简单的密封class,MyShape
:
public sealed class MyShape permits MyCircle {
private final int width;
private final int height;
public MyShape(int width, int height) {
this.width = width;
this.height = height;
}
public int width() {
return width;
}
public int height() {
return height;
}
}
还有一个简单的子class, MyCircle
:
public final class MyCircle extends MyShape {
public MyCircle(int width) {
super(width, width);
}
}
当两个 class 都在同一个包中时,一切都可以编译和工作。如果我将 MyCircle 移动到子包中,则构建中断:java: class is not allowed to extend sealed class: org.example.MyShape
.
根据 JDK 15 docs 我的理解是这应该有效。我错过了一步吗?
我已经 created a GitHub repo 如果你想试验的话。
如您链接的文档中所述:
They must be in the same module as the sealed class (if the sealed class is in a named module) or in the same package (if the sealed class is in the unnamed module).
我有一个简单的密封class,MyShape
:
public sealed class MyShape permits MyCircle {
private final int width;
private final int height;
public MyShape(int width, int height) {
this.width = width;
this.height = height;
}
public int width() {
return width;
}
public int height() {
return height;
}
}
还有一个简单的子class, MyCircle
:
public final class MyCircle extends MyShape {
public MyCircle(int width) {
super(width, width);
}
}
当两个 class 都在同一个包中时,一切都可以编译和工作。如果我将 MyCircle 移动到子包中,则构建中断:java: class is not allowed to extend sealed class: org.example.MyShape
.
根据 JDK 15 docs 我的理解是这应该有效。我错过了一步吗?
我已经 created a GitHub repo 如果你想试验的话。
如您链接的文档中所述:
They must be in the same module as the sealed class (if the sealed class is in a named module) or in the same package (if the sealed class is in the unnamed module).