“this” Keyword in Java

“this” Keyword in Java

  • this keyword is a reference to the current object within instance method or a constructor.
  • this () is used to invoke current class constructor.
  • this can also be used to pass an argument in the method call.

Example: Sample program for using this keyword

public class Rectangle
{
     int length, width;
     Rectangle(int length, int width)
     {
          this.length = length;
          this.width = width;
     }
     int areaCal()
     {
          return (length*width);
     }
     public static void main(String args[])
     {
          Rectangle rec = new Rectangle(53, 45);
          int area = rec.areaCal();
          System.out.println ("Area of Rectangle: "+area);
     }
}


Output:
Area of Rectangle: 2385

Example: Sample program for constructor calling

class ConDemo
{
     int empId;
     String name;
     ConDemo()
     {
          System.out.println("Default Constructor:");
     }
     ConDemo(int empId, String name)
     {
          this();      // invoked default constructor
          this.empId = empId;
          this.name = name;
     }
     void show()
     {
          System.out.println("Employee ID: "+empId+"  Name: "+name);
     }
     public static void main(String args[])
     {
          ConDemo con = new ConDemo(100,"XYZ");
          con.show();
     }
}


Output:
Default constructor:
Employee ID: 100  Name: XYZ