Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about this

 
Corrado Grabbi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In the past I've always taken the implicit "this" variable for granted, that is to say in a given instance it's a reference back to that instance.

Yesterday, whilst doing some technical online tests, I came across this notation, where "this" is seemingly referenced via a static member of the class type ( note this is how it seems from the syntax, not sure what actually is going on ), e.g.



Returning this.name in the toString method is self explanatory, but the Employee prefix is throwing me, the syntax implies that "this" is a static member of the Employee class, but this doesn't make sense given that the whole point of "this" is that is it's a reference per instance.

Can anyone elighten me on this?

Thanks
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Typically, you see syntax like that in Inner Classes, where the "this" reference would normally refer to the instance of the inner class instead of the instance of the enclosing class. If you prefix "this" with the enclosing class, you now have a reference to that instance.

Confused? Consider:



Note that in the line labeled 20, there is a MyPanel.this.doAction() call. You could just say "doAction()" and the compiler will figure it out -- but I don't like it because it breaks the subject-verb paradigm that I program in (but that's an argument for another thread).

But you can't say "this.doAction()," as the "this" refers to the instance of the anonymous ActionListener that we are creating. So, in order to get "this" to reference the MyPanel instance, we have to say "MyPanel.this.doAction()"
 
Corrado Grabbi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah yes - thanks.

Makes perfect sense in context of inner classes - I guess I was thrown as I'd never seen this syntax outside of inner classes.

Cheers
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic