this keyword : Refer Current Object in Java Programming
- this is keyword in Java.
- We can use this keyword in any method or constructor.
- this keyword used to refer current object.
- Use this keyword from any method or constructor to refer to the current object that calls a method or invokes constructor .
Syntax : this Keyword
this.field

Live Example : this Keyword
class Rectangle {
int length;
int breadth;
void setDiamentions(int ln,int br)
{
this.length = ln;
this.breadth = br;
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.setDiamentions(20,10);
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
}
}Output :
C:Priteshjava>java RectangleDemo
Length of Rectangle : 20
Breadth of Rectangle : 10
this Keyword is used to hide Instance Variable :
void setDiamentions(int length,int breadth)
{
this.length = length;
this.breadth = breadth;
}- length,breadth are the parameters that are passed to the method.
- Same names are given to the instance variables of an object.
- In order to hide instance variable we can use this keyword. above syntax will clearly make difference between instance variable and parameter.
Pingback: Learn Java Programming Language Step by Step : Index : Learn Java Programming Language Tutorials