How is the this key word used in Java | SoloLearn: Learn to code for FREE!

-1

How is the this key word used in Java

4/27/2020 3:00:55 PM

Bakka Solomon Mwesigwa

2 Answers

New Answer

+1

The keyword this is used to refer to the current object of a class.

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. } }