Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why interface can only be declared in top-level class?

Alright, I know it's the rule:

According to JLS: 8.1.3 Inner Classes and Enclosing Instances, inner classes may not declare static initializers or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields.

According to 8.5.2 Static Member Type Declarations, "Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier". They are always top-level, not inner.

I just wonder why. What may happen if we are allowed to declare interface within an inner class? Won't inner class become top-level class if I put it into another Class file?

like image 657
Luke Vo Avatar asked Aug 23 '11 15:08

Luke Vo


1 Answers

Won't inner class become top-level class if I put it into another Class file?

No, it still is an inner class, which the filename indicates (IIRC it's OuterClass$InnerClass.class).

Inner classes have access to the outer class' attributes, i.e. they depend on their outer class' instance. With interfaces you couldn't do this. Think of a completely unrelated class that would have to be created by the corresponding outer class' instance. How would that be done if the outer class doesn't know who implements that interface?

What you can do is declare static interfaces in your outer class, thus merely using the outer as a namespace:

public class OuterClass {
  public static interface InnerInterface { //protected and private would be fine too, depending on what makes sense
  }
}

Edit: actually, I misread the question and since interfaces are static anyways, here's an updated code snippet:

 public class OuterClass {
  public static InnerClass { //static inner class making OuterClass just be a namespace
     public interface InnerInnerInterface { //protected and private would be fine too, depending on what makes sense
     }
  }
}

As a workaround you could define an abstract inner inner class, with the drawback that you have to stick to the single inheritance constraint.

like image 120
Thomas Avatar answered Nov 15 '22 20:11

Thomas