this keyword in java

In Java ,this is keyword which can be used inside a method or constructor of a class. It can be used to refer current object data member,invoke current object method,invoke  parameterized constructor inside another constructor.

Usage of this keyword

  • this keyword is used to refer to current object.
  • this keyword can be used to invoke current class constructor.
  • this  keyword  can be passed as an argument to another method.
  • this keyword  can be used to invoke current class method.

Example of this keyword with instance variable

this keyword used inside a method or constructor to refer current object instance variable. Here this keyword is used to differentiate local variable and instance variable.

class Rectangle
 {
  private int length,breadth;
  Rectangle(int length, int breadth)
  {
    this.length  = length;
    this.breadth = breadth;
  }
}

Example of this keyword to invoke constructor

class Rectangle
 {
  private int length,breadth;
  Rectangle()
  {
   this(10,8); //It will invoke  Rectangle(int length, int breadth)
  }
  Rectangle(int length, int breadth)
  {
    this.length  = length;
    this.breadth = breadth;
  }
}

Example of this keyword to invoke method

class Rectangle
 {
  private int length,breadth;
  public void displayLength(){
   System.out.println("Lenght"+length);
  }
 public void displayBreadth(){
   System.out.println("Breadth"+breadth);
  }
  public void display(){
   this.displayLength();
   this.displayBreadth();
  }
}

Leave a Reply