Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding the usage of "this reference" in Java  RSS feed

 
John Stuart
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assume this code:



How exactly 'this' work in line 15? As far as I know, 'this' can be used to refer to a class's field that got shadowed in a method and to refer to another constructor in a class (overloaded constructor).
I can't seem to get my head around in this one. Also there's a method definition for checkMonth and checkDay but I omitted it here for the sake of brevity.

And is it true that all object has its own toString method that implicitly called when an object is to be presented in its string format? Or it can be explicitly called when the user concretely defined it in a class.
 
Oliver Refle
Greenhorn
Posts: 1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The keyword 'this' is a reference to the enclosing object. In your case your constructor passes a reference of the current Date object into the System.out.printf ()method.
When using this to asign fields its a similar approach. Instead of using the local method scope you reference the field of the current object by using this as a prefix. In below example if you would leave out the this it would assign the field variable to the variable that exists in the local scope (in this case what you get as an argument).



It is true that some methods are calling toString() implicitly. This also happens when you do something like .

Hope that helps.



 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch (after getting on for 6 years).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!