this keyword in java with example (JNNC Technologies)


this keyword in java is used to refer to current object or instance of class. It can be used in constructor to call any other overloaded constructor but this keyword should be the first statement in the constructor.

This keyword can be used for instance variables:

this keyword can be used to refer to the instance variable of class.
When you run above program, you will get below output:
Employee’s name : John
Employee’s age : 20
As you can see we have used this keyword to set values for instance variable in the constructor.

This keyword can be used to call the overloaded constructor:

If you want to call overloaded constructor of same class, you can use this keyword to do that.
For example:
When you run above program, you will get below output:
Calling No arg constructor
Calling Parameterized constructor
Employee’s name : John
Employee’s age : 20
Please note that this keyword used for calling another constructor should be first statement in that constructor.

this keyword can be used return object of the class:

Calling No arg constructor
Employee’s name : John
Employee’s age : 20
that’s all about this keyword in java.

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();