java - 编译器没有发现实例变量和构造函数初始化期间传递的参数之间存在歧义?

标签 java constructor resolve ambiguity

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 关键字,编译器在解析实例变量和参数之间的相同名称时存在歧义。

为什么编译器能够在第一种情况下打印值?尽管那里也存在歧义!!

最佳答案

在构造函数内,所有不合格的 xy 引用参数,不是实例变量。仔细遵循这个逻辑,您就会明白为什么会得到这样的结果。

关于java - 编译器没有发现实例变量和构造函数初始化期间传递的参数之间存在歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877320/

相关文章:

java - 创建子类时父类(super class)打印意外值

php - 使用 PHP 解析 URL 中的相对路径

java - 如何检查 boolean 值直到它为真

java - 标签 'select' ,字段 'list' ,名称 'uuid' : The requested list key 'deptList' could not be resolved as a collection/array/map/enumeration/iterator type

java - 子类构造函数是否需要父类(super class)构造函数的所有参数?

c++ - C++中的延迟构造函数

python - 如何处理基于 git 的 wiki 中的 merge/冲突?

javascript - 在 javascript 的 .then() 子句中调用两个 Promise

java - Spring Data Neo4j 4.1 中的树/层次结构建模

java - 我应该使用哪个 Point2D