JDK 15 Sealed Classes - how to use across packages?
Asked Answered
S

1

9

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.

Succedaneum answered 17/9, 2020 at 21:44 Comment(0)
M
5

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

Mutual answered 17/9, 2020 at 22:23 Comment(1)
Thanks but I think you've bolded the wrong portion of the text. If I had not been using the unnamed module, then having MyCircle in a different package would have worked as expected. If the question is "how to use across packages" then the answer is "don't use the unnamed module."Succedaneum

© 2022 - 2024 — McMap. All rights reserved.