![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
this keyword is used to refer current object of a class.The members of the current object like instance method or field can be referred by using this pointer.
The current execution of object is always pointed by this pointer called as 'object under execution'.
class WithoutThis { int value; String msg; WithoutThis(String msg,int value) { msg = msg; value = value; } void display() { System.out.println("Without This\n"); System.out.println("Message : "+msg); System.out.println("Value : "+value); } public static void main(String args[]) { WithoutThis wt = new WithoutThis(); } }
Output
In above example we have initialized two variables using Parameterized Constructor. When we run the program we get output as shown above because, in constructor current class fields are not referred that's why values are assigned to same variable only.
Example - Using this keyword
class WithThis { int value; String msg; WithoutThis(String msg,int value) { this.msg = msg; this.value = value; } void display() { System.out.println("With This\n"); System.out.println("Message : "+msg); System.out.println("Value : "+value); } public static void main(String args[]) { WithThis wt = new WithThis(); } }
Output
In above example we have used this keyword to refer current class values. that's why have get proper result.
this keyword is also used for calling the constructor functions. It is written inside the constructor to call another constructor
Note : this must be the first statement in the constructor call
Syntax
className() { this(parameter1,parameter2...parameterN); ... ... }
Example
class ThisWithCon { ThisWithCon() { this(1); System.out.println("Im Default "); } ThisWithCon(int a) { this("AndroidBerry",2); System.out.println("P1"); } ThisWithCon(String a, int b) { System.out.println("P2 "); } public static void main(String args[]) { ThisWithCon twc = new ThisWithCon(); } }
Output
In above example we have created an object of class called twc. this object called to the default constructor function but, in default constructor we have used this() keyword to call constructor with 1 argument to call Parameterized constructor P1 but P1 again calls for the P2.