• Post Reply Bookmark Topic Watch Topic
  • New Topic

A problem with "this" reference  RSS feed

 
Peng Fan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
we know keyword this refer to the current class's object, is that mean in every class there is a static variable named this implicitly added by compiler, so in some cases, we can use ClassName.this.someVariable syntax.
what on earth does the keyword mean from this case?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is best viewed as a parameter implicitly passed to every instance method and constructor.

It contains a reference to a class instance (object). In the case of a constructor, this points to an allocated and partially initialized object which the constructor will continue to initialize. In the case of an instance method, this points to the object on which the metod was called.



In this example, the constructor MyClass() will be called by the new operator with this pointing to the object being created.
Later, myMethod will be called with this set to second.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the Java Langage Specification:

15.8.4 Qualified this
Any lexically enclosing instance can be referred to by explicitly qualifying the keyword this.

Let C be the class denoted by ClassName. Let n be an integer such that C is the nth lexically enclosing class of the class in which the qualified this expression appears. The value of an expression of the form ClassName.this is the nth lexically enclosing instance of this (�8.1.2). The type of the expression is C. It is a compile-time error if the current class is not an inner class of class C or C itself.


In your example,
ClassName.this.someVariable
ClassName must be an enclosing class to the class containing the method you are in. this points to that instance of the enclosing class that has the instance you are now in as a member. The structure is used to allow an instance method of an enclosed class to reference instance members of the enclosing class.

In no case is this a static variable.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!