+ 3

Can somebody plz explain the this.x??

12th Mar 2017, 8:40 PM
jad zoghaib
jad zoghaib - avatar
8 odpowiedzi
+ 15
"this" keyword refers to the current object. It is used to differentiate field variable from local variable if both have same name. this.x means the x field of the current object. When we pass a variable x to a constructor or method, it becomes a local variable. If we pass x=3 as argument, then this.x = x; // this.x = 3 means that the field x of current object is assigned as 3.
12th Mar 2017, 8:54 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 14
Local variables are declared inside a method and this variable can only be used within that particular method. But global variables are declared inside the class so that ALL methods can use it.
12th Mar 2017, 8:58 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 12
@jad, this.x means the x which has been declared as field variable of class. x means the argument value of constructor or method, which has been passed from caller method (main or any other).
12th Mar 2017, 9:06 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 12
See this example code if needed: https://code.sololearn.com/cpHx2iuWqzWt/?ref=app
12th Mar 2017, 11:34 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 5
this refers to the current instance of the class/object. You can access variables/methods from the class using this. Example: (ignoring writing main method and class, just assume the program starts here and has the following code:) public int test = 5; void method(){ int anotherInt = this.test; } In this example anotherInt goes to the instance of the class, grabs the test variable and sets it equal to anotherInt. this is a useful keyword for OOP.
12th Mar 2017, 9:00 PM
Rrestoring faith
Rrestoring faith - avatar
0
difference between local and global variable?
12th Mar 2017, 8:54 PM
jad zoghaib
jad zoghaib - avatar
0
so this.x means that we're working with the x of the constructor and x means that we're working with the x of the main class??
12th Mar 2017, 9:00 PM
jad zoghaib
jad zoghaib - avatar
0
ok thank you
12th Mar 2017, 9:08 PM
jad zoghaib
jad zoghaib - avatar