package learning;
public class This_keyword {
int x;
int y;
This_keyword(int x,int y){
x = x;
y = y;
System.out.print("Value of 1st :" +x);
System.out.print("Value of 2nd :" +y);
}
public static void main(String args[]){
This_keyword sample = new This_keyword(4,5);
}
}
这应该打印 0,0,因为我没有使用此关键字,但它仍然打印 4,5,它们作为参数化构造函数传递。
现在看看第二个代码,
package learning;
public class This_keyword {
int x;
int y;
This_keyword(int x,int y){
x = x;
y = y;
}
void display(){
System.out.print("Value of 1st :" +x);
System.out.print("Value of 2nd :" +y);
}
public static void main(String args[]){
This_keyword sample = new This_keyword(4,5);
sample.display();
}
}
现在是 printng 0,0,这是预期的,也是正确的,因为没有提到 this 关键字,编译器在解析实例变量和参数之间的相同名称时存在歧义。
为什么编译器能够在第一种情况下打印值?尽管那里也存在歧义!!
最佳答案
在构造函数内,所有不合格的 x
和 y
引用参数,不是实例变量。仔细遵循这个逻辑,您就会明白为什么会得到这样的结果。
关于java - 编译器没有发现实例变量和构造函数初始化期间传递的参数之间存在歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877320/