猿问

无法理解.this关键字在此代码中的使用

请说明代码,无法理解main()方法中的test(3).x是什么意思


class Test { 

     int x=0; 

     static int y=1;

     Test(){  

      this.y++;

      this.x+=++x;  

      }


    Test(int x){   

      this();

      System.out.println(x+this.x+this.y);

      }

    }



    public class MyClass {

       public static void main(String args[]) {

         System.out.println(new Test(3).x+" "+new Test(4).y);

    }


}


繁华开满天机
浏览 123回答 2
2回答

侃侃无极

Test(3)这意味着您正在调用参数化的构造函数Test(int x),并将3的值传递给x。this关键字用于引用该类的当前对象。当使用this.variable名称时,表示在类的范围内引用了与当前对象关联的变量(正在使用“ new”关键字,例如创建新对象new Test(3).x)。因此,参数化的构造函数将相应地被调用,并且其中包含的任何代码将由编译器相应地解析。
随时随地看视频慕课网APP

相关分类

Java
我要回答