Java this keyword



this keyword : Refer Current Object in Java Programming

  1. this is keyword in Java.
  2. We can use this keyword in any method or constructor.
  3. this keyword used to refer current object.
  4. 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

this keyword in Java Programming Language Class Concept

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.