What is the use of "this" keyword in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the use of "this" keyword in java

6th Oct 2019, 2:30 AM
CodingIsFun
CodingIsFun - avatar
3 Answers
6th Oct 2019, 2:34 AM
voja
voja - avatar
+ 1
Refers to a field variable and not a local one
6th Oct 2019, 2:59 AM
Odyel
Odyel - avatar
+ 1
In a java class definition, 'this' refers to the current instance of the class. (The actual instance will be created outside of the class with the 'new' keyword.) It is used to access the instance variables and methods. Example: it is conventional to use in getter / setter methods but also anywhere else when you refer to instance variables. class Bucket { // instance variable private bool isEmpty; // setter public void setEmpty(bool isEmpty) { this.isEmpty = isEmpty; } } Here the isEmpty instance variable will take the value that is passed in the parameter of the setter method.
6th Oct 2019, 4:02 AM
Tibor Santa
Tibor Santa - avatar