• Post Reply Bookmark Topic Watch Topic
  • New Topic

object variables - this. vs. its  RSS feed

 
Dennis Schroeder
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java I commonly see this:




From C++ I'm used to write this:



Are these different in functionality (I'd assume not), is one recommended over the other ?
 
Campbell Ritchie
Marshal
Posts: 56527
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The construct this.something means the something which belongs to the object (i.e. the field) rather than the local variable/parameter. Note that in Java® this is a keyword.
There is no functional difference between the two versions, but using this. allows you to choose the best name for the field and expose it via the parameters. You must not however try the following sort of code:-I presume you already know why.
 
Dennis Schroeder
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.

Your above code would give a name clash, i.e. it would assign the local variable number to the local variable number (and not to the object variable as intended), and so does nothing, correct ?
 
Campbell Ritchie
Marshal
Posts: 56527
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Spot on
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Also, as a side note, why is a C++ naming convention being compared with the Java "this" keyword/mechanism? C++ also has a "this" keyword/mechanism, and it's behavior and purpose is almost identical to that of Java. Isn't that a better comparison?

Henry
 
Campbell Ritchie
Marshal
Posts: 56527
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look up hiding in our FAQ and in the Java® Language Specification (=JLS).
 
Dennis Schroeder
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong,

you're right. C++ also has the 'this' keyword with similar (same ?) functionality as in Java, it's just that in the C++ book I was learning from it was never used in the context of object variables.

So my question was more wondering if the way I already knew from C++ can by applied the same in Java or if there's any difference, rather than comparing the this keyword itself in both languages.

Hope this clears it up.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!