+ 3
Can somebody plz explain the this.x??
8 Answers
+ 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.
+ 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.
+ 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).
+ 12
See this example code if needed:
https://code.sololearn.com/cpHx2iuWqzWt/?ref=app
+ 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.
0
difference between local and global variable?
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??
0
ok thank you