I think the reason new Test().new C().i works is because the Test class is a top-level class and is considered static . If you changed your inner class C to static, then new C().i would work.
However, you must NOT access static members in an unsteady manner.
To access your static field:
System.out.println(Ci);
Edit:
For those who say that the Test class is not static, refer to this stackoverflow description.
All top-level classes are, by definition, static.
What static is reduced to the fact that the class instance can stand on its own. Or vice versa: a non-static inner class (= inner class of an instance) cannot exist without an instance of an outer class. Since the top-level class does not have an outer class, it cannot be anything but static.
Since all top-level classes are static, with the static keyword in the definition of a top-level class is pointless.
Just to show you how a dumb idea is to access a static field, so I created the following project:
class Test { class C { static final int i = 0; } public static void main(String[] args) { // BAD: System.out.println(new Test().new C().i); // Correct: System.out.println(Ci); } }
If you compile the class and view it in jd-gui , you can see how it was compiled:
class Test { public static void main(String[] args) { void tmp13_10 = new Test(); tmp13_10.getClass(); new C(); System.out.println(0); System.out.println(0); } class C { static final int i = 0; C() { } } }
Jared rummler
source share