Please explain the code, unable to understand what test(3).x means in the main method
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
can be rewritten in this form:
Test myObject = new Test(3);
myObject.x
which you might be more familiar with.
All it does is create a Test
object and access that object's x
field.
The program prints
6
8
1 3
The first constructor call makes y
be 2, and this.x
be 1. x+this.x+this.y
, which is 3+1+2=6, is then printed. The second constructor call makes y
be 3, and this.x
be 1. x+this.x+this.y
, which is 4+1+3=8, is then printed.
Now the whole expression new Test(3).x+" "+new Test(4).y
is evaluated. new Test(3).x
is 1, and Test.y
is 3. These two values are then printed.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments