The this Keyword


The this is a keyword in Java which is used as a reference to the object of the current class, within an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables, and methods. In general, the keyword this is used to
  • Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
class Student {
  int age;   
  Student( int age ) { this.age = age; }
}
  • Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
class Student {
  int age;
  Student( ) { this( 20 ); } 
  Student( int age ) { this.age = age; }
}

The example uses this keyword to access the members of a class:

ThisExample.java (the this keyword)
public class ThisExample {
  // Instance variable num
  private int num = 10;
       
  public static void main( String[ ] args ) {
    // Instantiating the class
    ThisExample obj1 = new ThisExample( );
    // Invoking the print method
    obj1.print( );
    // Passing a new value to the num variable through parametrized constructor
    ThisExample obj2 = new ThisExample( 30 );
    // Invoking the print method again
    obj2.print( );
  }
  public ThisExample( ) {
    System.out.print( num + " " );
  }
  public ThisExample( int num ) {
    // Invoking the default constructor
    this( );
    // Assigning the local variable num to the instance variable num
    this.num = num;   
  }   
  public void greet( ) {
    System.out.print( num + " " );
  }
  public void print( ) {
    // Local variable num
    int num = 20;    
    // Printing the local variable
    System.out.print( num + " " );
    // Printing the instance variable
    System.out.print( this.num + " " );
    // Invoking the greet method of a class
    this.greet( );     
  }
}
Output:           Result:




      A penny for your thoughts, and half a penny for your land