Interface is not allowed inside methods

I have looked into some books for OCPJP 7 certification and there was some strange / incomplete information at the head of the inner classes. I tried to create an interface inside a method, but you can't seem to do that, you can create classes inside a method. Is there any reason you can't do this or is this just a missing feature?

Sample code:

public class Outer {
  public void method() {
    class C {} // allowed
    interface I {} // interface not allowed here
  }
}

      

+3


source to share


1 answer


If you read the Java Tutorials carefully , you will see that:

You cannot declare an interface inside a block, because interfaces are inherently static.

This means that if you have an interface like:

public class MyClass {
   interface MyInterface {
       public void test();
   }
}

      



You can do

MyClass.MyInterface something = new MyClass.MyInterface() {
    public void test () { .. }
};

      

because it MyInterface

will be obvious static

. It doesn't make sense to bind to an instance of the enclosing class, because it just provides some abstraction that doesn't have to be tied to a specific instance or state of the enclosing class.

The same thing happens when the interface is nested within a method. Nothing inside a method can be (explicitly) static

(because non-static methods are bound to a specific instance of a class-class) and therefore you cannot have a local interface.

+5


source







All Articles