Java 中的静态块 [英] Static Block in Java

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

问题描述

前几天我正在查看一些代码,我发现:

I was looking over some code the other day and I came across:

static {
    ...
}

来自 C++,我不知道为什么会出现这种情况.这不是错误,因为代码编译得很好.这个静态"代码块是什么?

Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?

推荐答案

这是一个 静态初始化器.它在类加载(或初始化,准确地说,但您通常不会注意到差异)时执行.

It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).

它可以被认为是一个类构造函数".

注意还有实例初始值设定项,除了没有 static 关键字外,它们看起来相同.当创建对象的新实例时,除了构造函数中的代码之外,它们还会运行.

Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.

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

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