Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

keyword this  RSS feed

 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the code: I do not understand the keyword this in this context. It seems that it does not make any sense. You could write the following code: The result is the same, it prints 5. It seems to make no sense to use the keyword this, you can omit it. It is allowed to use the keyword this in this context, thus there must be a reason.

There is an other use of the keyword this I do not understand: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.3

Let us have a look at this line: How do you explain this line?
 
Author and ninkuma
Marshal
Posts: 66684
167
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this, used as a prefix, indicates the current instance. Inside an instance, it is frequently able to be omitted, and is defaulted. Some style guides recommend always using the this prefix for clarity.

In the latter example, again, this refers to the current instance and is being compared for identity with whatever the variable other is referencing.

Think of this as a variable that is automatically added to scopes within an instance context, that is automatically set as a reference to the instance.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The line:  is checking current instance of class with the other (other is also an instance of IntVector class).
You using this keyword to specify that the variable you are using is belong to current class.
For example with a setter method:



In that you let the compiler know what 'a' is variable of current class and what 'a' is the parameter.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66684
167
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Nguyen Tuyen wrote:In that you let the compiler know what 'a' is variable of current class ...


No really. It's a reference to the instance, not the class.
 
Bring out your dead! Or a tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!