In Java, this is a reference variable, this can be used inside any method or constructor to refer to the current object.
Following demonstrating the use of this
1 2 3 4 5 6 | volume(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } |
Use of this Keyword in constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Student { String name; int marks; Student(String name, int marks) { this.name = name; //use of this this.marks = marks; // use of this } void display() { System.out.println("Name: " + name + " marks:" + marks); } } public class main { public static void main (String[] args) { Student st = new Student("Daniel", 90); st.display(); } } |
Output:
Name: Daniel marks:90
Note: that, Java does not allow to declare two local variables with the same name inside the same or enclosing scopes, so the use of the same parameter name and data-members(instance variable) is possible because of this operator.
this keyword used within the constructor refers to the instance variable of that constructor or class.
In the above example, this.name = name, this.name refers to the instance variable whereas the name on the right side refers to the parameter value. and equal(=) sign assign parameter value to an instance variable. Also called Instance Variable Hiding.
If we do not use this keyword violating the Java declaration process, we get the following result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Student { String name; int marks; Student(String name, int marks) { name = name; //not using of this marks = marks; //not using of this } void display() { System.out.println("Name: " + name + " marks:" + marks); } } public class main { public static void main (String[] args) { Student st = new Student("Daniel", 90); st.display(); } } |
Output:
Name: null marks:0
this Keyword: to pass as an argument in the method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Method { void m1(Method obj) { System.out.println("This is method m1"); } void m2() { m1(this); } } class Main { public static void main (String[] args) { Method m = new Method(); m.m2(); } } |
Output:
This is method m1
this: Invoke current class method:
The method of the current class can be invoked by using this keyword. If this keyword is not used then the compiler automatically adds this keyword while invoking the method.
source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Method { void m1() { System.out.println("This is method m1"); } void m2() { System.out.println("This is method m2"); this.m1(); } } class Main { public static void main (String[] args) { Method m = new Method(); m.m2(); } } |
Output:
This is method m2
This is method m1