请解释代码,无法理解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);
}
}
答案 0 :(得分:1)
Test(3)
表示您正在调用参数化的构造函数Test(int x)
,并将3的值传递给x。 this
关键字用于引用该类的当前对象。使用this.variable名称时,意味着您正在引用与该类中的范围内的当前对象关联的变量(您正在使用“ new”关键字,例如new Test(3).x
创建一个新对象)。因此,参数化的构造函数将被相应地调用,编译器将相应地解析其中包含的任何代码。
答案 1 :(得分:0)
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。然后打印这两个值。