nits.kk nits.kk - 5 months ago 25
Java Question

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.

Answer
  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).