Java空块范围 [英] Java empty block scope
本文介绍了Java空块范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道使用空块的目的是什么。例如,
I am wondering what's the purposes of using empty block. For example,
static{
int x = 5;
}
public static void main (String [] args){
int i = 10;
{
int j = 0 ;
System.out.println(x); // compiler error : can't find x ?? why ??
System.out.println(i); // this is fine
}
System.out.println(j); //compiler error : can't find j
}
有人可以解释
- 在什么情况下我们想要使用空块。
- 是所有变量在那个空块里面还是
stack
? - 为什么无法访问
静态变量x
?
- In what situation that we would want to use empty block.
- Are all the variables inside that empty block still goes on
stack
? - Why couldn't it access the
static variable x
?
推荐答案
- 您在帖子中显示的块是它不是空块,而是静态初始化器。它用于为类的静态变量提供非平凡的初始化
- 在初始化期间使用的局部变量进入堆栈,但从堆中分配的对象除外
- 您无法访问静态变量
x
,因为您没有声明它。相反,您在静态初始化程序中声明了一个局部变量x
。
- The block that you are showing in your post is not an empty block, it is a static initializer. It is used to provide non-trivial initialization for static variables of your class
- Local variables that you use during initialization go on stack, except for objects that you allocate from the heap
- You cannot access static variable
x
because you did not declare it. Instead, you declared a local variablex
inside a static initializer.
如果你想让 x
一个静态变量,然后在静态初始化块中初始化它,执行以下操作:
If you would like to make x
a static variable and then initialize it in a static initialization block, do this:
private static int x;
static {
x = 5;
}
在这样的琐碎案例中,一个简单的初始化语法最有效:
In trivial cases like this, a straightforward initialization syntax works best:
private static int x = 5;
初始化程序块保留用于更复杂的工作,例如,当您需要使用循环初始化结构时:
Initializer blocks are reserved for more complex work, for example, when you need to initialize structures using a loop:
private static List<List<String>> x = new ArrayList<List<String>>();
static {
for (int i = 0 ; i != 10 ; i++) {
x.add(new ArrayList<String>(20));
}
}
这篇关于Java空块范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文