Why are compile-time constants allowed for static in non-stationary inner classes?

Suppose we have code as shown below.

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

I understand that creating an object of non-stationary inner classes requires an object of class Outer . static means the class associated with it, and to access it, an object is not required to instantiate. A non-stationary inner class can only be used after we instantiate the Outer class. The presence of any static links in it may not make sense.

My questions:

  • Can a non-static inner class be loaded without any explicit object of the Outer class?

  • Why is compilation of time constants (string literals, since they are handled in a special way in the String pool and primitive types) allowed for static in a non-stationary inner class ?

Edit: why it is impossible to prohibit constant compilation constants statically, I know it as JLS, but I just want to know what would go wrong, what was the purpose of making this rule.

+3
source share
2 answers
  • Can a non-static inner class be loaded without any explicit object of the Outer class?

Yes. An instance of an inner class requires an instance of the outer class. But both classes can be loaded before creating any instances.

  1. Why do we have compile-time constants (string literals, since they are handled in a special way in the String pool and primitive types), can be made static in a non-stationary inner class?

The language specification allows this exception for constant variables. From the Java Language Specification, Section 8.1.3: "Inner Classes and Nested Instances" :

This is a compile-time error if the inner class declares a member that is explicitly or implicitly static, unless the element is a constant variable (ยง4.12.4).

And String variables can be constants due to section 4.12.4, " final Variables" :

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

+3
source

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

Yes, you can load a non-static inner class this way, see the example below:

 class MyObject { class InnerObject { static final String prop = "SOME INNER VALUE"; } static void doLoad() { System.out.println(InnerObject.prop); } } 

The fact is that there are not many reasons for this, because a non-stationary inner class cannot have any static blocks, methods, fields, if they are not final, as in the question below.

Question 2 . Why do we have compile-time constants (String literals, since they are handled in a special way in the String pool and primitive types), can be made static in a non-stationary inner class?

Java designed in such a way that you can use static , final fields in non-static inner classes.

0
source

All Articles