我申请了一份工作,他们给了我一个 Java 测试。有许多我不熟悉的未知概念,也有较新的概念。一个是关于静态字段。我在下面发布了一个最奇怪的问题并寻求帮助。
代码在注释中包含问题。
public class MyClass {
//what is the purpose of section, I mean for which purpose is it being used?
//can variables inside of belove section be used or not. If can be used, then how?
static{
int a=5;
double x=4.1;
}
//why this does not give any error because of redecleration of integer a?
static int a=4;
public static void main(String[] args) {
System.out.println(a+"");//the output is 4
}
}
最佳答案
这个 block
static{
int a=5;
double x=4.1;
}
被称为静态初始化器。当可能需要多个语句来初始化一个字段时,它用于初始化 static
字段。
但在这里,您实际上并没有初始化任何静态变量。您刚刚声明了两个局部变量。
这是重要的行:
static int a=4;
关于Java静态字段使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20200783/