Search code examples
javainner-classesanonymous-classlocal-classnested-types

Can we declare interface inside a method?


"You cannot declare an interface inside a block; interfaces are inherently static" This is sentence from https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html#local-classes-are-similar-to-inner-classes

However, I can declare an interface in the code below. I can also create an anonymous class by extending the interface.

public void testing() {
    
    interface LocalInterface {
        void prints();
    }
    
    LocalInterface localInterface = new LocalInterface() {

        @Override
        public void prints() {
            System.out.println("hello world");
        }};
        localInterface.prints();
}

Solution

  • Java 16+

    It depends on which JDK you are using. The interface-inside-a-method feature was introduced in JDK 16. Ditto for enum and record. See JEP 395: Records.

    If you are using IntelliJ, it will show you an error when JDK is set to 8. The error says: Local interfaces are not supported at language level '8', and the suggestion is upgrade to JDK 16+.

    enter image description here