Java 'this' Keyword: Usage and Examples
Table of Content:
There can be a lot of usage of java this
keyword. In java, this is a reference variable
that refers to the current object.
Usage of java this keyword
Here is given the 6 usages of java this keyword.
- this can be used to refer current class instance variable.
- this can be used to invoke current class method (implicitly)
- this() can be used to invoke the current class constructor.
- this can be passed as an argument in the method call.
- this can be passed as an argument in the constructor call.
- this can be used to return the current class instance from the method.
1. this() keyword refer current class instance variable
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; float salary; Employee(int id,String name,float salary){ id=id; name=name; salary=salary; } void display(){ System.out.println(id+" "+name+" "+salary); } } class ThisKeyword{ public static void main(String args[]){ Employee e1=new Employee(12121,"Dhinchak Pooja",50000f); Employee e2=new Employee(112,"Hero Alom",60000f); e1.display(); e2.display(); } }
Output:
0 null 0.0 0 null 0.0 Press any key to continue . . .
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
Solution of the above problem by this keyword
class Employee{ int id; String name; float salary; Employee(int id,String name,float salary){ this.id=id; this.name=name; this.salary=salary; } void display(){ System.out.println(id+" "+name+" "+salary); } } class ThisKeyword{ public static void main(String args[]){ Employee e1=new Employee(12121,"Dhinchak Pooja",50000f); Employee e2=new Employee(112,"Hero Alom",60000f); e1.display(); e2.display(); } }
Output:
12121 Dhinchak Pooja 50000.0 112 Hero Alom 60000.0 Press any key to continue . . .
Program where this keyword is not required
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
class Employee{ int id; String name; float salary; Employee(int i,String j,float k){ id=i; name=j; salary=k; } void display(){ System.out.println(id+" "+name+" "+salary); } } class ThisKeyword{ public static void main(String args[]){ Employee e1=new Employee(12121,"Dhinchak Pooja",50000f); Employee e2=new Employee(112,"Hero Alom",60000f); e1.display(); e2.display(); } }
Output:
12121 Dhinchak Pooja 50000.0 112 Hero Alom 60000.0 Press any key to continue . . .
2. this can be used to invoke current class method
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 TestClass{ void method1(){ System.out.println("This is method1"); } void method2(){ System.out.println("This is method2"); //method1();//same as this.method1() this.method1(); } } class ThisKeyword{ public static void main(String args[]){ TestClass a=new TestClass(); a.method2(); } }
Output:
This is method2 This is method1 Press any key to continue . . .
3. this() can be used to invoke the current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.
Calling default constructor from parameterized constructor:
class Message{ Message(){ System.out.println("hello a"); } Message(int p){ this(); System.out.println(""p); } } class ThisKeyword{ public static void main(String args[]){ Message a=new Message(12); } }
Output:
hello a 12 Press any key to continue . . .
Calling parameterized constructor from default constructor:
class Message{ Message(){ this(5); System.out.println("Not- parameterized Hello Bro"); } Message(int p){ System.out.println("parameterized constructor "+p); } } class ThisKeyword{ public static void main(String args[]){ Message a=new Message(); } }
Output:
parameterized constructor 5 Not- parameterized Hello Bro Press any key to continue . . .
4. this can be passed as an argument in the method call.
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 ThisKeyword{ void method1(ThisKeyword obj){ System.out.println("method is invoked"); } void method2(){ method1(this); } public static void main(String args[]){ ThisKeyword s1 = new ThisKeyword(); s1.method2(); } }
Output:
method is invoked Press any key to continue . . .
Another Example:
class ThisKeyword2{ int a = 12; void method1(ThisKeyword2 obj){ System.out.println("method is invoked"); System.out.println(obj.a); } void method2(){ method1(this); } public static void main(String args[]){ ThisKeyword2 s1 = new ThisKeyword2(); s1.method2(); } }
Output:
method is invoked 12 Press any key to continue . . .
5. this can be passed as an 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 classA{ ThisClass obj; classA(ThisClass obj){ this.obj=obj; } void display(){ System.out.println(obj.data);//using data member of ThisClass class } } class ThisClass{ int data=12; ThisClass(){ classA b=new classA(this); b.display(); } public static void main(String args[]){ ThisClass a=new ThisClass(); } }
Output:
12 Press any key to continue . . .
6. this can be used to return the current class instance from the method.
We can return 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 statement from the method
class classA{ classA getA(){ return this; } void msg(){ System.out.println("java at atnyla"); } } class ThisKeyword{ public static void main(String args[]){ new classA().getA().msg(); } }
Output:
java at atnyla Press any key to continue . . .
Detail view
When this( ) is executed, the overloaded constructor that matches the parameter list
specified by arg-list is executed first. Then, if there are any statements inside the original
constructor, they are executed. The call to this( )
must be the first statement within the
constructor.
To understand how this( ) can be used, let’s work through a short example. First,
consider the following class that does not use this( ):
class Smile{ int a; int b; // initialize a and b individually Smile(int i, int j) { a = i; b = j; } // initialize a and b to the same value Smile(int i) { a = i; b = i; } // give a and b default values of 0 Smile( ) { a = 0; b = 0; } void display(){ System.out.println("a = "+a+" and b = "+b); } } class ThisKeyword{ public static void main(String args[]){ Smile sm = new Smile(); sm.display(); } }
Output:
a = 0 and b = 0 Press any key to continue . . .
This class contains three constructors, each of which initializes the values of a and b. The first is passed individual values for a and b. The second is passed just one value, which is assigned to both a and b. The third gives a and b default values of zero.
By using this( ), it is possible to rewrite MyClass as shown here:class Smile { int a; int b; // initialize a and b individually Smile(int i, int j) { a = i; b = j; } // initialize a and b to the same value Smile(int i) { this(i, i); // invokes Smilet(i, i) } // give a and b default values of 0 Smile() { this(0); // invokes Smile(0) } void display(){ System.out.println("a = "+a+" and b = "+b); } } class ThisKeyword{ public static void main(String args[]){ Smile sm = new Smile(); sm.display(); } }
Output:
a = 0 and b = 0 Press any key to continue . . .
In this version of Smile
, the only constructor that actually assigns values to the a and
b fields is Smile(int, int)
. The other two constructors simply invoke that constructor
(either directly or indirectly) through this( )
. For example, consider what happens when this
statement executes:
class ThisKeyword{ public static void main(String args[]){ Smile sm = new Smile(); sm.display(); } }
Smile sm = new Smile();
a = 0 and b = 0 Press any key to continue . . .In this case,
this(0)
is called. This causes Smile(0)
to be invoked because it is the
constructor with the matching parameter list. Of course, Smile(0) then calls Smile(0,0)
as just described
Now,
class ThisKeyword{ public static void main(String args[]){ Smile sm = new Smile(10); sm.display(); } }
Smile sm = new Smile(10);
a = 10 and b = 10 Press any key to continue . . .The call to Smile(10) causes
this(10, 10)
to be executed, which translates into a call to
this(10, 10)
, because this is the version of the Smile constructor whose parameter list
matches the arguments passed via this( )
. Now, consider the following statement, which
uses the default constructor: