• Post Reply Bookmark Topic Watch Topic
  • New Topic

this keyword  RSS feed

 
Raj Gurung
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please could anyone let me know about this keyword in following program:



thanks
 
Junilu Lacar
Sheriff
Posts: 11490
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raj Gurung wrote:please could anyone let me know about this keyword in following program:

this in the given code refers to the instance of the S2 class that was created on line 10 and referenced by s1
 
Raj Gurung
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks.
So that means, in this program this refers to 2 instance of class S2 created in this program: s1 and s2.
is it correct???



 
Junilu Lacar
Sheriff
Posts: 11490
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think your code will compile: Line 14 - cannot invoke method o that way. Also, it would be a great courtesy to people you are asking to help you if you formatted your code properly. That ragged indentation is without rhyme or reason and is just bad coding style.
 
Raj Gurung
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops sorry,

actually its s2.o();

now it will compile.
thanks
 
Junilu Lacar
Sheriff
Posts: 11490
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line 13 - the p() method is invoked on the instance referenced by s1, which is what this refers to on line 6

Line 14 - the o() method is invoked on the instanced referenced by s2, which is what this refers to on line 8

this simply refers to the object on which the method was invoked. It's easier to follow if you gave more meaningful names, rather than cryptic ones like m, o, and p. You just make things difficult for yourself that way. You are saving keystrokes at the expense of brain cells and brain power.

Note that you don't normally see this used the way you have it in your examples. A reference to this is usually passed to other objects, which is a way of saying "Hey, ObjectX, do what you need to do using me (this object)". Typically, this is how callbacks are implemented. That means an object, call it the "invoker", passes a reference to itself when invoking a method on another object, say the "processor". The "processor" keeps a reference to the "invoker", does something, then "calls back" to report results to the original calling object, the "invoker". Does that make sense?
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!