请解释代码,无法理解test(3(.x在main方法中的含义
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);
}
}
new Test(3).x
可以用这种形式重写:
Test myObject = new Test(3);
myObject.x
您可能更熟悉。
它所做的只是创建一个Test
对象并访问该对象的x
字段。
程序打印
6
8
1 3
第一个构造函数调用使y
为 2,this.x
为 1。 然后打印x+this.x+this.y
,即 3+1+2=6。第二个构造函数调用使y
为 3,this.x
为 1。 然后打印x+this.x+this.y
,即 4+1+3=8。
现在计算整个表达式new Test(3).x+" "+new Test(4).y
。new Test(3).x
为 1,Test.y
为 3。然后打印这两个值。
这里的Test(3)
意味着您正在调用参数化的构造函数Test(int x)
并将值 3 传递给 x。this
关键字用于引用类的当前对象。当您使用 this.variable name 时,这意味着您引用的是与类中作用域中的当前对象关联的变量(您正在使用 "new" 关键字 Eg. 创建一个新对象。new Test(3).x
(。因此,参数化构造函数将被相应地调用,并且其中的任何代码都将由编译器相应地解析。