Java: why is there no warning when referencing a field before defining it?

Static fields cannot be referenced until defined or initialized:

static Integer j = i; /* compile error */
static final Integer i = 5;

However, when it is referenced from an instance initialization block (in an anonymous inner class), no warning is even generated

See example:

class StaticInitialization {

    static final Object o = new Object() {{
        j = i;
    }};

    static Integer j,k;
    static final Integer i = 5;

    static final Object o2 = new Object() {{
        k = i;
    }};
}

The result is: J = = null, k = = 5, so it is clear that we made a reference, the command is important, and there are no warnings or compilation errors

Is this code legal?

Solution

Is this code legal? Probably I don't think it's the compiler's job to analyze your intentional side effects of object instantiation in patching static variables

Limited analysis from other static "before declaration" in the same category is indeed only a help to the most common boos, not a guarantee of the imprint of indirect errors

I'm not really surprised that "declare before reference" analysis is limited in scope, and direct access to static variables is in other static declarations This is a simple & compact analysis with minimum complexity, very fast

Extending it to consider the side effects of object instantiation & method calls, Otoh, will require 20-1000 times more weight & static program analysis range Static analysis requires access to potentially entire compiler code, using constraint based calculations to determine what might happen and how long it might run in minutes

Considering these choices, in the shoes of Java language designers, it is quite easy to choose simple analysis to cover direct access to fields in the same class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>