Having trouble understanding .this keyword use in this code

arnab das

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);
    }

}
Sweeper

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.

edited at
0

Comments

0 comments
Login to comment

Related

Having trouble understanding a portion of code

Having trouble understanding this assembly code

Haskell - Having trouble understanding a small bit of code

Having trouble understanding a portion of code (bit operation)

Having Trouble Understanding How To Use Singleton Pattern?

Group by and having trouble understanding

Having trouble understanding currying

Having trouble understanding part of my code, The Fisher–Yates shuffle

Having trouble understanding what this test case code is doing

I am having trouble understanding part of an ExceptionError code

Buffer to integer. Having trouble understanding this line of code

I'm having trouble understanding the syntax used in a piece of code

Having trouble understanding the upper bound and lower bound in the following R code

Having some trouble understanding middleware

Having trouble understanding lbu instruction

Having trouble understanding pointer operations

Having trouble understanding the map() method

Having trouble understanding call signatures

Having trouble understanding sequence diagrams

Having trouble understanding ajax calls

Async and await - having trouble understanding

Having trouble displaying code

Trouble understanding this assembly code

Why is there no server.emit in this code and i am having trouble understanding this code in node js?

Understanding the use of the keyword every

I'm having trouble understanding why a single click in my code is selecting text

Having trouble understanding the logic of this while loop

Having trouble understanding interface/struct relationship

Having trouble understanding this javascript destructuring statement

TOP Ranking

HotTag

Archive