This keyword in Java



Following are the usage of this keyword. 

  • this can be used to get the current object.
  • this can be used to invoke current object's method.
  • this() can be used to invoke current class constructor
  • this can be passed as a parameter to a method call.
  • this can be passed as a parameter to a constructor.
  • this can be used to return the current object from the method.

Example

Live Demo

public class Tester {
   private String message;
   public Tester(String message){
      this.message = message;
   }
   public void printMessage(){
      System.out.println(message);
   }
   public static void main(String args[]) {
      Tester tester = new Tester("Hello World");
      tester.printMessage();
   }
}

Output

Hello World

Here this keyword is used to get the current object and then gets its variable.


Advertisements