JDK 15 封闭类 – 如何跨包使用?

huangapple go评论63阅读模式
英文:

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

如您所提供的文档所述:

JDK 15 文档

> 它们必须与密封类位于相同的模块(如果密封类位于命名模块中)或者与密封类位于相同的包中(如果密封类位于未命名模块中)

英文:

As stated in the documentation that you have linked:

JDK 15 Documentation

> 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).

huangapple
  • 本文由 发表于 2020年9月18日 05:44:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63946541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定