英文:
JDK 15 Sealed Classes - how to use across packages?
问题
我有一个简单的密封类,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;
}
}
还有一个简单的子类,MyCircle
:
public final class MyCircle extends MyShape {
public MyCircle(int width) {
super(width, width);
}
}
当这两个类都在同一个包中时,一切都可以编译和工作。但是,如果我将 MyCircle
移动到一个子包中,构建过程就会出错,显示:java: class is not allowed to extend sealed class: org.example.MyShape
。
根据JDK 15文档中的理解,这应该是可以工作的。我是否遗漏了什么步骤?
如果你想尝试,我已经在GitHub存储库中创建了示例代码。
英文:
I have a simple sealed 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;
}
}
And one simple subclass, MyCircle
:
public final class MyCircle extends MyShape {
public MyCircle(int width) {
super(width, width);
}
}
Everything compiles and works when both classes are in the same package. If I move MyCircle into a sub-package, then the build breaks with: java: class is not allowed to extend sealed class: org.example.MyShape
.
My understanding from the JDK 15 docs is that this should work. Am I missing a step?
I've created a GitHub repo if you want to experiment.
答案1
得分: 5
如您所提供的文档所述:
> 它们必须与密封类位于相同的模块(如果密封类位于命名模块中)或者与密封类位于相同的包中(如果密封类位于未命名模块中)。
英文:
As stated in the documentation that you have linked:
> 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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论