Why are interfaces static?

前端 未结 4 847
星月不相逢
星月不相逢 2020-12-19 08:33

Why can I not have a interface inside of a inner class? Why are they inherently static? Sorry if it\'s a stupid question, I\'ve tried my best to google this aga

4条回答
  •  粉色の甜心
    2020-12-19 08:57

    Why are they [interfaces] inherently static?

    The difference between a static and a non-static nested class is in whether their instances have implicit references to enclosing instances (of the containing class), as well as to local variables from the containing scope. Before Java 8, there was no way for an interface to make use of such implicit references, because an interface could not initialize any non-static fields or provide any method implementations. (It still can't initialize non-static fields, though now it can provide default method implementations.) So before Java 8, there was no meaning in a non-static nested interface.

    Also, from an implementation standpoint, these implicit references are implemented as an extra fields on the inner class, and they also require extra arguments to the inner-class constructor (in order to initialize these fields). Interfaces don't have fields, or constructors, so there's no way to implement this.

    (Note: I don't usually recommend trying to understand language design decisions in terms of the implementation, because a single language feature can have many different correct implementations. But I think this is one case where understanding the implementation helps to understand the specification, hence the previous paragraph.)

提交回复
热议问题