Java类和静态块 [英] Java classes and static blocks

查看:93
本文介绍了Java类和静态块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Hello12 {
    static int b = 10;
    static {
        b = 100;
    }
}

class sample {
    public static void main(String args[]) {
        System.out.println(Hello12.b);
    }
}

在运行上面的代码时,输​​出为100,因为当我调用了Hello类,首先执行静态块,将b的值设置为100并显示它。
但是当我写这段代码时:

On running above code the output comes as 100 because when I called Hello class, static block is executed first setting the value of b to 100 and displaying it. But when i write this code:

class Hello12 {
    static {
         b = 100;
    }
    static int b = 10;
}

class sample {
    public static void main(String args[]) {
        System.out.println(Hello12.b);
    }
}

此处输出为10.我期待回答因为一旦执行了静态块,它就将b赋值为100.所以当在main()中,我调用 Hello.b 时,它应该引用b(= 100)。如何在两个代码中分配给b的内存?

Here the output comes as 10. I am expecting answer as 100 because once the static block is executed it gave b the value as 100. so when in main(), I called Hello.b it should have referred to b (=100). How is the memory allocated to b in both the codes?

推荐答案

在类的详细初始化过程中, JLS的第12.4.2节说明:

In the "Detailed Initialization Procedure" for classes, Section 12.4.2 of the JLS states:


接下来,执行类的类变量初始值设定项和静态初始值设定项,或接口的字段初始值设定项,按文本顺序,好像它们只是一个块。

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

这意味着它好像第一个例子是:

This means that it's as if the first example was:

b = 10;
b = 100;

第二个例子是:

b = 100;
b = 10;

最后一项作业获胜,解释你的输出。

The last assignment "wins", explaining your output.

这篇关于Java类和静态块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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