How is the this key word used in Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

How is the this key word used in Java

27th Apr 2020, 3:00 PM
Bakka Solomon Mwesigwa
Bakka Solomon Mwesigwa - avatar
2 Answers
+ 1
The keyword this is used to refer to the current object of a class.
27th Apr 2020, 3:27 PM
Bahhaⵣ
Bahhaⵣ - avatar
0
It can for example be useful in constructors when you try to assign to your class variables, but the parameters for the constructors share the same name as your class variables. By using the "this" keyword you clarify that you want the class' own variable to be used instead of the parameter. class Person { String name; int age; public Person(String name, int age) { this.name = name; // Assign the name parameter to our class variable. this.age = age; // Assign the age parameter to our class variable. age += 5; // Increases the parameter by 5 this->age++; // Increases class variable by 1. } }
27th Apr 2020, 3:59 PM
Damyian G
Damyian G - avatar