Are nested classes inside an interface implicitly static and final?

耗尽温柔 提交于 2019-12-13 07:25:23

问题


All variables inside of interface are public static and final.

So if I declare a nested class inside an interface will it also become static and final?

Interface I
{
    class c
    {
        static void m(){ }
    }
}

回答1:


Lets find out. Lets create structure like:

interface Interface{
    class Foo{}
}

Now we can test:

System.out.println("static: " + Modifier.isStatic(Interface.Foo.class.getModifiers()));
System.out.println("final: " + Modifier.isFinal(Interface.Foo.class.getModifiers()));

which prints:

static: true
final: false

So nested classes are implicitly static, but not final.

We can confirm it also by adding class Bar extends Foo{} to our interface. final classes can't be extended but since such code compiles fine it means Foo is not final.




回答2:


Classes nested inside interfaces behave like static classes nested inside classes, in the sense that you do not need to have an instance of an outer class in order to construct an instance of a nested class. According to Java Language Specification, §8.1.3:

8.1.3 Inner Classes and Enclosing Instances

[...] A member class of an interface is implicitly static (§9.5) so is never considered to be an inner class.

However, these classes are not final, unless you explicitly designate them as such. This makes sense, because classes that implement an interface may need an opportunity to extend nested classes defined inside the interface.



来源:https://stackoverflow.com/questions/43541045/are-nested-classes-inside-an-interface-implicitly-static-and-final

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!