this keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class’ type is permitted. Example is as follows :
class UseOfThis { int length = 10; int breadth = 20; void show(int length, int breadth) { System.out.println(this.length); // to refer to above length System.out.println(this.breadth); // to refer to above breadth System.out.println(length); System.out.println(breadth); } } public class Rec { public static void main(String[] args) { UseOfThis obj = new UseOfThis(); obj.show(30, 40); } }
Output
10 20 30 40