Java this Keyword:
- It can be used within the law or the constructor of class.
- Works as a reference to the current object whose method or constructor is being used.
- Java this keyword can be used to reference any member of the existing object from within an example method or constructor.
Syntax:
1 | this.data_member_of_current_class |
Example:
1 2 3 4 5 6 7 8 9 10 | class Test { Double width, height, depth; Test (double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } } |
Note: Here it is used to start the member of the current object. As such, this.width refers to the variable width of the current object, which has implemented the constructor. Width refers to the parameter only found in the constructor.
this keyword instance variable:
- this keyword can be very useful in managing hiding in java this keyword.
- We can not create two examples / local variables with the same name.
- Although it is legal to create an example variable with a variable or a local variable or the same name.
this keyword with the constructor:
- The keyword “this” can be used within the constructor, which can be called an overloaded constructor call in the same class.
- This happens when Class 2 is overloaded constructs, with the second argument without argument, the keyword “this” can then be used to call the constructor without reasoning from the constructor with reasoning.
this keyword with the method:
- this keyword can also be used within methods to call any other method from the same class.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | package package_Java; class This_Java { int id; String name; This_Java(int id, String name) { this.id = id; this.name = name; } void show() { System.out.println(id + " " + name); } public static void main(String args[]) { This_Java e1 = new This_Java(111, "Sandeep"); This_Java e2 = new This_Java(112, "Swapnil"); e1.show(); e2.show(); } } |
Output:
1 2 | 111 Sandeep 112 Swapnil |
Note: In the above example, parameter (formal arguments) and instance variables are same that is why we are using “this” keyword to distinguish between local variable and instance variable.