静态初始化块 [英] Static Initialization Blocks

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

问题描述

据我所知,如果不能在一行中完成,静态初始化块"用于设置静态字段的值.

As far as I understood the "static initialization block" is used to set values of static field if it cannot be done in one line.

但我不明白为什么我们需要一个特殊的块.例如,我们将一个字段声明为静态(没有赋值).然后编写几行代码,生成上面声明的静态字段并为其赋值.

But I do not understand why we need a special block for that. For example we declare a field as static (without a value assignment). And then write several lines of the code which generate and assign a value to the above declared static field.

为什么我们需要在一个特殊的块中使用这些行,例如:static {...}?

Why do we need this lines in a special block like: static {...}?

推荐答案

非静态块:

{
    // Do Something...
}

被调用每次构造类的实例.静态块只会在类本身初始化时调用一次,无论您创建了多少该类型的对象.

Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.

示例:

public class Test {

    static{
        System.out.println("Static");
    }

    {
        System.out.println("Non-static block");
    }

    public static void main(String[] args) {
        Test t = new Test();
        Test t2 = new Test();
    }
}

打印:

Static
Non-static block
Non-static block

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

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