Java – why can interfaces only be declared in top-level classes?

OK, I know this is the rule:

I just want to know why and what might happen if interfaces were allowed to be declared in internal classes? If I put it in another class file, won't the inner class become the top class?

Solution

No, it is still an internal class, indicated by the file name (IIRC, it is outerclass $innerclass. Class)

Inner classes can access the properties of outer classes, that is, they depend on their outer class' instances You can't do this using the interface Think of a completely unrelated class that must be created by the corresponding external class' instance What if the external class doesn't know who implements the interface?

What you can do is declare a static interface in an external class, so only use the external as a namespace:

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

Editor: actually, I misunderstood the problem because the interface is static. Here is an updated code fragment:

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 solution, you can define an abstract inner class. The disadvantage is that you must adhere to a single inheritance constraint

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>