• Post Reply Bookmark Topic Watch Topic
  • New Topic

Usage of "this" in parameter keyword.  RSS feed

 
Shankara Sharma
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have seen a declaration as follows:

Class Prototype{

Prototype(){
Request request=new Request(this);// What does this statement mean?
}
}

Can anyone please explain me the usage to this as an actual argument?

Thanks,
Shankar
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is a keyword and it refers to "the current object", in other words, the object that the current method is called on. In your example, it's the Prototype object.

Note that in your particular example you're passing this from inside constructor of a Prototype object. That's dangerous: the current Prototype object is still under construction, so you're passing a not-yet-fully-initialized object to the constructor of class Request. That can lead to subtle, hard to debug problems, if the constructor of Request counts on the Prototype object that's passed to it to be fully initialized. It's not a good idea to pass this from inside a constructor to somewhere outside the class.
 
Shankara Sharma
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks..
Is this one similar to passing object as an argument?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, this is just like a special kind of variable that always refers to the object that the current method was called on. You could also do this:

Remember however what I said about passing this to somewhere outside the constructor; you're passing a Prototype object which is not fully initialized, which can lead to strange problems.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!