Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

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

Suppose we have code as below.

public class Outer{
    class Inner{
        public static final String s = "abc";
    }
    static class Nested{
        public static final SomeOtherClass instance = new SomeOtherClass();
    }
} 

I understand to instantiate object of non static inner classes an object of Outer class is needed. static means class related and for accessing it an object is not required to be instantiated. Non static inner class can only be used once we have an object of Outer class instantiated. Having any static references in it may not make sense.

My Questions:

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

  2. Why 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 ?

Edit : Why can not non compile time constants be allowed to be made static, I know its as per JLS, but just wish to know what would have gone wrong, what was the intent to make this rule.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...