Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' in Java: How does it work?

Tags:

java

I know that 'this' is acting as reference in Java. We can use it inside the class members only.

What I am asking is... because it is used in the members of the class, that means it has to be either an instance variable or parameter.

And assume, if it is param to a method but it is working in blocks. block does not contain any params and all ..could you explain what is it ...how exactly it was defined in java?How exactly it is using By JVM.

like image 310
anil Avatar asked Aug 05 '10 09:08

anil


1 Answers

From a linguistic point of view, this is neither a local variable or a parameter. Syntactically, it is a keyword. Semantically, it is an explicit way of saying "the current object"; see JLS 15.8.3. For example:

  • this.<attributeName> explicitly refers to an instance level attribute of the current object.
  • <methodName>(this) calls a method, passing a reference to the current object as an explicit argument.

The this keyword has other uses in Java that don't exactly mean "the current object":

  • this(<optArgumentList>) as the first statement in a constructor chains to another constructor in the same class; JLS 8.8.7.
  • <className>.this within an inner class refers to the instance of an enclosing class for the current object; JLS 15.8.4.

From an implementation perspective, you can think of the "this" reference as a hidden or implicit parameter that gets passed each time an instance method is called. Indeed, this is more or less how the object reference is treated by the JVM's "invoke*" bytecodes. You push the target object reference onto the "opstack" followed by each of the argument values, then execute the "invoke..." instruction. (Look here for the details.).

like image 66
Stephen C Avatar answered Oct 08 '22 21:10

Stephen C