执行初始化程序块和变量定义等的顺序是什么? (在java中) [英] In what order are initializer block and variable definitions and etc. executed? (in java)

查看:143
本文介绍了执行初始化程序块和变量定义等的顺序是什么? (在java中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有理解初始化发生的顺序。这是我假设的订单:

I have problem understanding the order in which initialization happens. this is the order I assumed:

*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 am 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;
    }

如果我这样做,错误就会消失:

And the error would disappear if I do this:

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

我无法弄清楚为什么不存在

I can't figure out why isn't there an error on

    b=0;


推荐答案

Java语言规范(第8.3.2.3节)说您可以在表达式的左侧使用变量,即在声明之前赋值给它,但是您不能在右侧使用它。

The Java Language Specification (section 8.3.2.3) says you can use a variable on the left hand side of an expression, i.e. assign to it, before it is declared, but you cannot use it on the right hand side.

所有变量都初始化为默认值,然后显式初始化器和匿名块按源文件中的顺序运行。最后调用构造函数。

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

静态只在第一次使用类时运行一次。

Statics are only run once on the first use of a class.

编译错误似乎是Java的规则,而不是在每种情况下都必须有意义的东西。

The compile error appears to be a rule of Java rather than something that necessarily makes sense in every case.

这篇关于执行初始化程序块和变量定义等的顺序是什么? (在java中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆