Java – this keyword

PREV     NEXT

  • The keyword ‘this’ is used to represent current object of the class. It is used to access various elements of the class like instance variables and methods. For eg: “this.var1” and “this.method1()”
  • The keyword ‘this’ when used along with parenthesis as in ‘this()’, is used to invoke the constructor of the class
  • ‘this’ keyword is used to differentiate the instance variable from the local variable, when both use the same name.
  • ‘this’ keyword can be passed as an argument to a method or a constructor and can even be used as a return parameter after a method execution like “return this;”

Example 1:

‘this’ used to refer the current instance variable

COMPILE & RUN

Output:

Width:5.0            Height:3.0

Example 2:


‘this()’ used to invoke constructor of the current class

COMPILE & RUN

Output:

Object created…

Width:5.0            Height:3.0

Example3:


‘this’ can be passed as an argument and can also be provided as the return value.

COMPILE & RUN

Output:

Width:5                Height:6

Width:4                Height:5

volume of the box:30

Width:5                Height:6

In the above program, the return type of the volume() method is Box. Thus, b.volume() returns the object reference of the class invoking it.

Hence b1 = b.volume(); logically means b1 = b;

Thus b’s instance variables are copied in b1 and hence b1.print() displays the same instances that of b.

PREV     NEXT

Share this website !!!
Facebook Twitter Linkedin