为什么下面的代码可以编译成功?
第二条
int a = 2
定义在int a = 2
范围内,为什么能编译成功?class Test { int a = 1; // variable a, { int a = 2; //duplicate variable } } public class Main { public static void main(String[] args) { System.out.println(new Test().a); } }
最佳答案
int a = 2;
是实例初始化 block 的局部变量。因此,它作为局部变量添加到 Test
类的每个构造函数的主体中。允许局部变量与实例变量同名(例如,这允许您有一个构造函数,其参数名称与相应实例变量的名称相同)。它们只是隐藏同名的实例变量(如果您想引用实例变量,则强制您使用 this.
限定名称)。
class Test {
int a = 1;
{
int a = 2;
}
}
相当于:
class Test {
int a = 1;
public Test ()
{
int a = 2;
}
}
虽然这段代码没有任何意义(因为我们从不使用局部变量 a
的值),但有 2 个名为 a
的变量(一个是局部变量,另一个是一个实例变量)在下面的例子中是有意义的:
class Test {
int a = 1;
public Test (int a)
{
this.a = a;
}
}
关于java - 为什么编译器不生成重复错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51692951/