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?
Advertisement
Answer
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.