What is the order in which initialization blocks and variable definitions are executed? (in Java)

I understand the order in which initialization occurs This is my hypothetical order:

*Once per 
    1. Static variable declaration
    2. Static block
*Once per object
    3. variable declaration
    4. initialization block
    5. constructor

But according to this code, I'm obviously wrong:

class SomethingWrongWithMe
    {
        {
            b=0;         //no. no error here.
            int a = b;   //Error: Cannot reference a field before it is defined.
        }
        int b = 0;
    }

If I do, the error will disappear:

class SomethingWrongWithMe
    {
        int b = 0;
        {
            b=0;
            int a = b;   //The error is gone.
        }
    }

I don't know why there are no mistakes

b=0;

Solution

The Java language specification (section 8.3.2.3) says that you can use the variable on the left of the expression on the left side of the declaration, that is, assigned to it, but you cannot use the variable on the right side

All variables are initialized to default values, and then explicit initialization and anonymous blocks run in the order in the source file Finally, the constructor is called.

Static learning can only be run once when using the course for the first time

Compilation errors seem to be a rule of Java, not every situation makes sense

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
分享
二维码
< <上一篇
下一篇>>