Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface is not allowed inside methods

I have studied some books for OCPJP 7 certification and in the inner classes chapter there were some strange/incomplete informations. I've tried to create an interface inside a method, but it seems you can't do that, you can only create classes inside a method. Is there any reason why you can't do that or it's just a missing feature?

Sample code:

public class Outer {
  public void method() {
    class C {} // allowed
    interface I {} // interface not allowed here
  }
}
like image 311
Silviu Burcea Avatar asked Aug 07 '14 10:08

Silviu Burcea


1 Answers

If you read carefully the Java Tutorials, 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 this one:

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

You will be able to do

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

because MyInterface will be explicitly static. It doesn't make sense to be tied to an instance of the enclosing class, because it just provides some abstraction which doesn't have to be bound to a specific instance or a state of the enclosing class.

Same thing goes to the case, in which the interface is nested in a method. Nothing inside the method could be (explicitly) static (because non-static methods are tied to a specific instance of the enlosing class) and thus you can't have a local interface.

like image 178
Konstantin Yovkov Avatar answered Oct 27 '22 16:10

Konstantin Yovkov