Tutorials

Java Keywords


Java this keyword


The keyword ‘this’ in java is used to refer to entity of the current class.

The entity may be an object, variable, method or constructor. When you use this with any one of them that means you are referring to current one.

 

The keyword ‘this’ can be used:

  • To refer to current class instance variable
  • To refer to current class method
  • To refer to current class constructor

Use this to refer current class instance variable

Many a time we come across a programming logic where method or constructor’s local variable shadow the current class instance variable.

In such scenario there might occur ambiguity in referring to local variable and instance variable.

See below code snippet for understanding the ambiguity issue.

 

Example: Applying this to refer to instance variable of current class that has been shadowed by constructor or methods local variable having same name.


public class Students {

      int id;
      String name;

      Students(int id, String name){

            this.id = id;
            this.name = name;
      }

}

In the above code snippet, 

this.id → refers to instance variable 'id' of the class Student

id → refers to local variable 'id' inside constructor

 

this.name→ refers to instance variable 'name' of the class Student

name → refers to local variable 'name' inside constructor

 
If this keyword was not used then it would have become difficult for the compiler to understand which id or name is being refered to. 
Suppose you had written,
id = id;
name = name;
instead of 
this.id = id; and this.name = name;
then local variable id and name would have got assigned to itself rather than being assigned to instance variable id and name.

 

 

 

 



Please Share this page
Views : 31