Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there such a thing as a "local interface" in Java?

Java allows me to define local abstract classes, like in this example:

public class Foo {

    public void foo() {
        abstract class Bar {          // Bar is a local class in foo() ...
            abstract void bar();
        }

        new Bar() {                   // ... and can be anonymously instantiated
            void bar() {
                System.out.println("Bar!");
            }
        }.bar();
    }
}

For some reason, when I try to define a "local interface" instead of the local class, like this:

public class Foo {

    public void foo() {
        interface Bar {           // Bar was supposed to be a local interface...
            void bar();
        }

        new Bar() {               // ... to be anonymously instantiated
            void bar() {
                System.out.println("Bar!");
            }
        }.bar();
    }
}

Java complains that "The member interface Bar can only be defined inside a top-level class or interface". Is there a reason for this? Or am I missing a mistake I made?

like image 242
Markus A. Avatar asked Dec 15 '22 01:12

Markus A.


1 Answers

There simply isn't a definition for it in the JLS. It just doesn't exist.

As for a weak reason, according to the JLS 14.3:

All local classes are inner classes (§8.1.3).

An interface can't be inner (JLS 8.1.3):

Member interfaces (§8.5) are implicitly static so they are never considered to be inner classes.

So we can't have a local interface.

This is, I guess, in addition to what @SotiriosDelimanolis has found that InterfaceDeclaration is not a BlockStatement.

like image 71
Radiodef Avatar answered Dec 31 '22 23:12

Radiodef