I've been coding in Java since 2005 and never thought that the code like that would actually be compilable:
public class FooClass {
public static final String FOO = FooClass.FOO;
}
Intellij IDEA calls it "initialized with self assignment". If someone showed me this code and asked whether it will compile or not, I would be 100% sure it should be a compilation error, as the variable was not actually explicitly assigned to any value.
I am bit shocked, because even such a nonsense as below appears to be legit:
public class FooClass {
public static final String FOO_1 = FooClass.FOO_2;
public static final String FOO_2 = FooClass.FOO_1;
}
No brainer, that such a variable appear to contain null value effectively. But Gosh, why?
I bumped into this piece of code in my project, because it was source of a bug. Someone did a refactoring and replaced the actual string constant with this self reference. Convince me that this is not a Java language bug, because otherwise it is a nasty way to shoot oneself in the foot!
UPD: I tested it on Java 21 only.
FooClass.FOO), you’re disabling the initialized check. Had you writtenFOO = FOOyou would have received the compiler error.FooClass.FOOis neither a simple name nor qualified withthis. Hence, it’s not an access in the sense of the remainder of the section which restricts the matching accesses to be only allowed when the variable is definitely assigned.