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

查看:99
本文介绍了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).

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

It can be thought of as a "class constructor".

请注意,还有实例初始值设定项,看起来相同,只是它们没有 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天全站免登陆