This keyword in java:
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 usage of java this keyword.
1. This can be used to refer current class instance variable.
2. This can be used to invoke current class method (implicitly)
3. This() can be used to invoke current class constructor.
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 can be used to return the current class instance from the method.
this: to refer current class instance variable:
The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, 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:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10.void display(){System.out.println(rollno+" "+name+" "+fee);}
11.}
12.class TestThis1{
13.public static void main(String args[]){
14.Student s1=new Student(111,"ankit",5000f);
15.Student s2=new Student(112,"sumit",6000f);
16.s1.display();
17.s2.display();
18.}}
Output:
0 null 0.0
0 null 0.0
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:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10.void display(){System.out.println(rollno+" "+name+" "+fee);}
11.}
12.
13.class TestThis2{
14.public static void main(String args[]){
15.Student s1=new Student(111,"ankit",5000f);
16.Student s2=new Student(112,"sumit",6000f);
17.s1.display();
18.s2.display();
19.}}
Output:
111 ankit 5000.0
112 sumit 6000.0
If local variables(formal arguments) and instance variables are different, there is no
need to use this keyword like in the following program:
Program where this keyword is not required:
Class Student{
Int rollno;
String name;
Float fee;
Student(int r,String n,float f){
Rollno=r;
Name=n;
Fee=f;
Void display(){System.out.println(rollno+” “+name+” “+fee);}
}
Class TestThis3{
Public static void main(String args[]){
Student s1=new Student(111,”ankit”,5000f);
Student s2=new Student(112,”sumit”,6000f);
S1.display();
S2.display();
}}
Output:
111 ankit 5000.0
112 sumit 6000.0