What is ‘this’ keyword in java?
The keyword ‘this’ in java is used to refer to the object that is invoked. It can be used inside any method which refers to the current object. So it acts as the reference to the object on which the method is invoked.
What are the uses of ‘this’ keyword?
‘this’ keyword in Java can be used in following situations.
- It can be used to invoke current class constructor
- It can be used to return the current class instance
- It can be used to refer current class instance variable
- It can be used to invoke the current class methods
‘this’ keyword with class instance variable in Java
We can use ‘this’ keyword to refer to the Current Object’s instance variables. This is very helpful especially when we have local variables or passed parameters have the same name as instance variable(s).
for example, If a method taking arguments has the same name as instance variables of the class and if we want to refer the local variables, simply we can use the local variable in the code, but If we want to use the Instance variable we can use this.VariableName. using this.variableName, JVM knows that in the method it needs to perform operation based on the value on instance variables instead of the locale variable.
Java’s Plain POJO (Plain Old Java Objects) or Beans in server terminology now a days are the best examples of using ‘this’ keyword. As we know POJO has instance variables and getters and setter methods of these Instance variables in the Class, in these getters and setters we always use this.variablename to set the value or to get the value.
‘this’ keyword in Java with current class method
This keyword is used to invoke the current class constructor when we have many constructors in the class and want to reuse that constructor. For example, If you want to call a constructor from within another constructor, then you can use this.ConstructorName() to invoke the constructor.
we can also use this keyword to call current class non static methods.
We cannot use this keyword in java within static blocks because static blocks are per Class not per instance/object.
java this() constructor