Enum that implements the interface, interface, and method visibility

I just moved on to the following code, which surprised me a little, but I converted it to a simple SSCEE:

custompackage.package1.MyEnum.java

public enum MyEnum implements MyInterface { CONSTANT_ONE() { @Override public void myMethod() { //do something very interesting } }, CONSTANT_TWO() { @Override public void myMethod() { //do something very interesting } }; } interface MyInterface { void myMethod(); } 

Now from outside this package, I can do the following:

 Consumer<MyEnum> myMethod = MyEnum::myMethod; 

However, I generally cannot use MyInterface , which I understand, since it is a private-package for custompackage.package1 .

I don’t understand what exactly is happening, but it seems that MyEnum received the myMethod() method, but it does not implement (externally) MyInterface .
How it works?

+7
java enums package-private interface
source share
3 answers

Well, you cannot see MyInterface from outside the package, as you said, but MyEnum effectively has the open abstract method myMethod() , which you can use as a method reference.

Leaving aside the new functionality of Java 8, this is valid (even out of the package):

 // Even MyEnum x = null; will compile, but obviously fail MyEnum x = MyEnum.CONSTANT_ONE; x.myMethod(); 

The method inherits from the interface, although the interface itself is not displayed.

This does not apply to interfaces and enumerations. For example:

 // Foo.java package foo; class SuperFoo { public void publicMethod() { } } public class Foo extends SuperFoo { } // Bar.java package bar; import foo.Foo; public class Bar { public void test() { Foo foo = new Foo(); foo.publicMethod(); } } 

This compiles fine, although Foo does not even override publicMethod . As for Bar , he inherited from somewhere, but he does not know where!

+4
source share

In interface methods, the default is public abstract . public static final fields

the reason you can use this method is because the interface is local. Try to make it public.

+1
source share

However, I generally cannot use MyInterface, which I understand, since it is a private package for custompackage.package1.

The interface is a private package, but all methods (and fields) are (implicitly or explicitly) public.

It seems that MyEnum got the myMethod () method, but it does not implement (externally) MyInterface.

MyEnum has a public method myMethod() , regardless of whether it inherits an (public) abstract method from an interface or whether it declares the method itself. On the other hand, even if the outside cannot see the interface, the outside can certainly see MyEnum and see MyEnum.myMethod() .

+1
source share

All Articles