简体   繁体   中英

Are nested classes inside an interface implicitly static and final?

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(){ }
    }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM