“this” keyword in java with examples

We will see the usage of “this” keyword one by one with examples –

  • “this” keyword refers to current class instance variables

When local variable and parameter variable are of same name, then “this” keyword is used to distinguish in between them.

local / parameterised variable hides the instance variable values called as variable hiding.

Example (same variable name for local and instance variable) –

out put: 

Parameterised variable id: 50
Instance variable id ‘using this’: 10
variable id ‘without using this’: 50

id (value 50) refers to local or parameterised variable inside dispData() method, but this.id (value 10) refers to the instance variable. 

NOTE: “this” keyword is a non static variable, we can not use “this” keyword in static context (in static methods and should not use for static members).

Example (different variable name for local and instance variable) –

no problem of distinguishing in between them and also no use of “this” is required to access them

output :

Parameterised variable id: 50
Instance variable i: 10

  • “this” keyword is used to call current class methods.

  • this() method is used to invoke current class constructor and this(“arg1”..) for parameterised constructor.

NOTE: invoking constructor by using this() should be the 1st statement.

Output:

this-constructor

parameterised this(arg1…) call –

output :

id: 12

NOTE: A constructor can either have this or super, but not both.

  • this keyword as an argument to method

output:

test Display()

  • return this statement

“return this;” is used to return current class instance, so the return type should be class type (not of any primitive type like int, string, void etc…)

Short link – bit.ly/qav-thiskeyword

Content posted is based on learning or working experience, please leave comments if anything needs to be added or updated, discuss your queries on our facebook:qavalidation.com, Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: