Why compile time constants are allowed to be made static in non static inner classes?

帅比萌擦擦* 提交于 2019-11-29 11:34:33
  1. Can non static inner class get loaded without any explicit object of Outer class ?

Yes. Creating an instance of an inner class requires an instance of the outer class. But both classes can be loaded before any instances are created.

  1. Why can we have compile time constants (String literals, as they are handled in special way in String pool and primitive types) are allowed to be made static in non static inner class ?

The language specification allows this exception for constant variables. From the Java Language Specification, section 8.1.3: "Inner classes and enclosing instances":

It is a compile-time error if an inner class declares a member that is explicitly or implicitly static, unless the member is a constant variable (§4.12.4).

And String variables can be constants, because of section 4.12.4, "final Variables":

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).

Question 1 - Can non static inner class get loaded without any explicit object of Outer class ?

Yes, you can load non-static inner class that way, look sample below:

class MyObject {
    class InnerObject {
        static final String prop = "SOME INNER VALUE";
    }

    static void doLoad() {
        System.out.println(InnerObject.prop);
    }
}

The thing is there are not many reasons to do so, because non-static inner class is not allowed to have any static blocks, methods, fields if those are not final as in a question below.

Question 2 - Why can we have compile time constants (String literals, as they are handled in special way in String pool and primitive types) are allowed to be made static in non static inner class ?

Java is designed so you can use static, final fields in non-static inner classes.

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