this Keyword

What is this keyword?
  • this is a keyword in java and used as a reference variable that refers to the current object. 
  • The main purpose of using this keyword is to differentiate the formal parameter and data members of class, whenever the formal parameter and data members of the class are similar then JVM get ambiguity (no clarity between formal parameter and member of the class).
Syntax:
this.data_member_of_current_class

ThisKeyword

Example:
Here the this is used to initialize member of current object.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Employee{
 int id;
 String name;

 Employee(int id, String name){
  this.id = id;
  this.name = name;
 }

 void show(){
  System.out.println(id + " " + name);
 }

 public static void main(String args[]){
  Employee e1 = new Employee(111, "John");
  Employee e2 = new Employee(112, "Lucky");
  e1.show();
  e2.show();
 }
}
Output:
111 John
112 Lucky

In the above example, parameter (formal arguments) and instance variables are same that is why we are using "this" keyword to distinguish between local variable and instance variable.



<-- Previous || Next -->

No comments:

Post a Comment