Java is the future !: What is "this" in Java

Thursday, August 26, 2010

What is "this" in Java

The "this" keyword can be used inside methods and constructors.

It returns the reference to the current object.

For example:

Here the setValue tries to set the value of the argument to the class variable n. Since the name n is already used in the method's parameter name, so n=n is absurd. The workaround is to use the “this” keyword to refer to the object. That's why we used “this.n=n”.

Another example of using “this” is when you need to pass your current object to another method.


In the above example, B has a member variable n. The method setMe calls another class method and passing itself as a object.

No comments:

Post a Comment