JAVA - "this" keyword

JAVA - "this" keyword

Let's understand what is the usage of "this" keyword in JAVA.

Whenever there is a naming Conflict between an instance variable and a local variable, this problem technically we call it as shadowing problem. To solve this problem we can use the "this" keyword to refer instance variable "this" will hold the address of the currently running object.

Example

In this example, the Employee class has 2 instance variables empId and empName. The constructor also takes 2 parameters and assigns them to the respective instance variables. The method empDisplay() is used to print the id and the name of the employee. In that method, we use "this" keyword to refer to the current instance of the Object. The parameters passed to the Constructor and instance variables have the same name, so to avoid confusion we use "this" keyword to represent the instance variable.

Here, we create an Object of an employee class and pass the respective parameter values. When the empDisplay() method is called it will print the name and id of the employee using "this" keyword.

"Thanks for Reading, I hope you found this post informative and helpful!"