sealed interfaces vs. default methods

Udo Höfel udo at hoefel.eu
Mon Jan 11 11:06:36 UTC 2021


Dear all,
I found some behavior of sealed generic interfaces with default methods that I find a bit unexpected. I put the examples from below also on GitHub ( https://github.com/uhoefel/java15_sealed_vs_default ).
Example:
Say we have an interface 

public sealed interface Interface<T> permits Impl_1 {}

and, separately, the implementation

public record Impl_1(Double value) implements Interface<Double> {}

Running the following works just fine:

public static void main(String[] args) {
    Interface<Double> q = new Impl_1(3.0);
    System.out.println(q instanceof Impl_1);
}

However, changing the interface to

public sealed interface Interface<T> permits Impl_1 {
	default int foo() {
		return 1;
	}
}

That is, adding just a simple default method to the interface produces the following compile error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Permitted type Impl_1 does not declare eu.hoefel.java15_sealed_vs_default.using_both.Interface<T> as direct super interface 

	at eu.hoefel.java15_sealed_vs_default.using_both.Interface.<clinit>(Interface.java:3)
	at eu.hoefel.java15_sealed_vs_default.using_both.Play.main(Play.java:5)

Putting the record inside the interface and removing the permits clause makes it work again, though:

public sealed interface Interface<T> {

	default int foo() {
		return 1;
	}

	public record Impl_1(Double value) implements Interface<Double> {}
}

I am on Windows 10 using 
openjdk version "15" 2020-09-15
OpenJDK Runtime Environment (build 15+36-1562)
OpenJDK 64-Bit Server VM (build 15+36-1562, mixed mode, sharing)

Also tested by a colleague with
openjdk version "15.0.1" 2020-10-20
OpenJDK Runtime Environment (build 15.0.1+9)
OpenJDK 64-Bit Server VM (build 15.0.1+9, mixed mode)

(Sorry if this doesn’t belong to this list)

Best regards & stay healthy,
Udo

-- 
Dr. Udo Höfel
Max Planck Institute for Plasma Physics, Branch Greifswald
Wendelsteinstraße 1 (Room: 7.1 003), D-17491, Greifswald, Germany
Phone: +49 (0)3834 88 1825
Fax:   +49 (0)3834 88 2509



More information about the amber-dev mailing list