Wednesday, 19 November 2014

What is use of this keyword ?


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

>1. this keyword can be used to refer current class instance variable.
>2. this() can be used to invoke current class constructor.
>3. this keyword can be used to invoke current class method (implicitly).
>4. this can be passed as an argument in the method call.
>5. this can be passed as argument in the constructor call.
>6. this keyword can also be used to return the current class instance.


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

See the problem without this keyword.Let's see the problem if we don't use this keyword by
the example given below:

class Student{
int id;
String name;
Student(int id,String name){
id = id;
name = name;
}
void show() {System.out.println(id+" "+name);}

public static void main(String []args){
Student s1 = new Student(123,"vishwa");
Student s2 = new Student(456,"karan");
s1.show();
s2.show();
   }
}

Output: 0 null
               0 null


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

Solution of the above problem by using this keyword:

class Student{
int id;
String name;
Student(int id,String name){
this.id = id;
this.name = name;
}
void show() {System.out.println(id+" "+name);}

public static void main(String []args){
Student s1 = new Student(123,"vishwa");
Student s2 = new Student(456,"karan");
s1.show();
s2.show();
   }
}

Output:123 vishwa
              456 karan

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:

Example where this keyword is not required:

class Student{
int id;
String name;
Student(int x,String y){
id = x;
name = y;
}
void show() {System.out.println(id+" "+name);}

public static void main(String []args){
Student e1 = new Student(123,"vishwa");
Student e2 = new Student(456,"karan");
e1.show();
e2.show();
   }
}

Output:123 vishwa
              456 karan

2> this() can be used to invoked current class constructor:

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

Example of this() constructor call.

class Student{
int id;
String name;
Student () { System.out.println("default constructor called");}
Student(int id,String name){
this (); //it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void show() { System.out.println(id+" "+name);}

public static void main(String []args){
Student s1 = new Student(123,"vishwa");
Student s2 = new Student(456,"karan");
s1.show();
s2.show();
  }
}

Output: default constructor called
              default constructor called
              123 vishwa
              456 karan


Que)Where to use this() constructor call?

Ans:The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of
this keyword.

class Student{
int id;
String name;
String city;
Student(int id,String name){
this.id = id;
this.name = name;
}
Student(int id,String name,String city){
this(id,name); //now no need to initialize id and name
this.city=city;
}
void show() { System.out.println(id+" "+name+" "+city);}

public static void main(String args[]){
Student s1 = new Student(123,"vishwa");
Student s2 = new Student(456,"karan","noida");
s1.show();
e2.show();
  }
}

Output: 123 vishwa null
              456 karan  noida

Note:Call to this() must be the first statement.

example for this senario:

class Student{
int id;
String name;
Student (){System.out.println("default constructor called");}
Student(int id,String name){
id = id;
name = name;
this ();// it must be the first statement within constructor
}
void show(){System.out.println(id+" "+name);}

public static void main(String []args){
Student s1 = new Student(123,"vishwa");
Student s2 = new Student(456,"karan");
s1.display();
s2.display();
  }
}

Output: compile time error

3> The this keyword can be used to invoke current class method (implicitly):

You may invoke the method of the current class by using the this keyword.If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example

class Student{
void A(){
System.out.println("method is invoked");
}
void B(){
this.A();//no need because compiler does it for you.
}
void C(){
B(); //complier will add this to invoke B() method as this.B()
}
public static void main(String []args){
Student s1 = new Student();
s1.C();
   }
}

Output: method is invoked

4> The this keyword can be passed as an argument in the method:

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:

class Student{
void A(Student obj){
System.out.println("method is invoked");
}
void B(){
A(this);
}
public static void main(String []args){
Student s1 = new Student();
s1.B();
  }
}

Output: method is invoked

5>The this keyword can be passed as argument in the constructor call:

We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example:

class B{
A obj;
B(A obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A class
   }
}

class A{
int data=10;
A(){
B b=new B(this);
b.display();
 }

public static void main(String []args){
A a=new A();
   }
}

Output: 10


6> The this keyword can be used to return current class instance:

We can return the this keyword as an statement from the method.In such case, return type of the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement:

return_type method_name(){
return this;
}

Example of this keyword that you return as a from the method:

class A{

A get(){
return this;// here this return object of class A
}
void msg() {System.out.println("Hello java");}

}

class Simple{
public static void main(String []args){
new A().get().msg();//here get() return instance of class A
  }
}

Output: Hello java


Proving that  this keyword refers to current class instance variable:

Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this,output of both variables should be same.

class Student{
void m(){
System.out.println(this);//prints same reference ID as obj
}
public static void main(String []args){
Student obj=new Student();
System.out.println(obj);//prints the reference ID
obj.m();
  }
}

Output: Student@19821f
               Student@19821f
















No comments:

Post a Comment