this Keyword in Java

this is a keyword in java which can be used inside a method or a constructor to refers to the current object. Except in static methods, this keyword can be used in any method to refer to current object. this keyword can be used to refer to any member variable or member method of current class.

this keyword can be used in multiple ways:

Uses of this Keyword in Java
  • We can declare instance variable and local variables inside a methods having same name. this can be used to differentiate between instance variable and local variable.

  • this can be used to refer to current object.

  • this can be used to invoke methods and constructors of current object.

  • this cab be used to pass current object as parameter to a method call.

  • this can be used to create copy of an object by passing it to the copy constructor.

  • this can be used to return current object from a method.

this can be used to refer to current object.

this keyword by default refers to the current object. Inside any member method, you can use this to access any member variable or to invoke any member method. This keyword is mainly used to distinguish between instance variable and local variable of same name.

this.variable will always refer to instance variable.


Using this to pass current object as parameter to a method

From a member method, if we want to invoke a method by passing current object then we can pass this as method argument. In this case called function must define current class as method argument.


Returning current object from a method

If we want to return current object from an instance method then we can simply return this. Here, instance method must define current class as it's return type.


this is used for constructor chaining

Using this we can call the constructor of a class like this(). this can also be used inside a constructor to invoke another overloaded constructor of same Class, this is called constructor chaining.
For example:
Let's say a class has one constructor without any argument and one constructor with one argument. From no-argument constructor we can call one argument constructor by passing some default value.