Example & Tutorial understanding programming in easy ways.

what is the 6 usage of this keyword in java?.

 There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current object


Usage of this keyword:

Here is given the 6 usage of this keyword:

a) this keyword can be used to refer current class instance variable.
b) this() can be used to invoke current class constructor.
c) this keyword can be used to invoke current class method (implicitly)
d) this can be passed as an argument in the method call.
e) this can be passed as argument in the constructor call.
f)  this keyword can also be used to return the current class instance.

 The this keyword can be used to refer current class instance variable.

If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:

class employee{

int id;

String name;

employee(int id,String name){

id = id;

name  =  name; }

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

public static void main(String args[]){

employee e1 = new employee(111,"aman");

employee e2 = new employee(321,"Arzoo");

e1.display();

e2.display();

} }

output:0 null;

0 null;

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.
 

Solution of the above problem by this keyword:-

example:-

class employee{

int id;

String name;

employee(int id,String name){

this.id = id;

this.name = name;

}

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

public static void main(String args[]){

employee e1 = new employee(100,"aman");

employee e2 = new employee(200,"Arzoo");

e1.display();

e2.display();

} }

output: 100 aman;

200 arzoo;

 

this() can be used to invoked current class constructor.

The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor.

example:

class employee{

int id;

String name;

employee (){System.out.println("default constructor is invoked");}

employee(int id,String name){

this ();//it is used to invoked current class constructor.

this.id = id;

this.name = name;

}

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

public static void main(String args[]){

employee e1 = new employee(100,"prag");

employeet e2 = new employee(200,"sonya");

e1.display();

e2.display();

} }

 Output: default constructor is invoked
                default constructor is invoked
                  100 prag
                   200 sonya


  

Read More →