• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance methods

 
Armstrong D
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the Mughal book, the explanation for Instance Method is given like this...
" The body of an instance method can access all members, including static members, defined in the class.
The reason is that instance methods are passed an implicit parameter which is a reference to the object on which the method is being invoked.
This is object can be referenced in the body of the instance method by the keyword this. "

I did not understand what he means by
-------------------------------------
"implicit parameter which is a reference to the object on which the method is being invoked. "
can anybody explain please
Thank you very much
Armstrong
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's take an example:

When method1() is invoked on the target object 'a', a reference to 'a' is implicitely passed to the method but that argument is not visible. For the compiler, the invocation looks like:
method1(a,"hello")
This is done so that you can use the reference to the object 'a' from within the instance method. This reference is called 'this' and you can use it to invoke other instance methods or access member variable. But 'this' is not mandatory, it is just syntactic sugar...
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only passably useful example of this that I know is when you use method parameters that happen to have the same name as your instance variables.
Suppose I have

and I want to assign the parameter x to the instance variable x. (of course, the obvious workaround is to rename the parameter, but let's just pretend we can't) You use the this reference to refer to the x of class Test

You can do this trick with constructors, initializer blocks and when you're fooling around with inner classes.
Don't confuse this with this() though. The latter is a totally different animal.
[ June 21, 2002: Message edited by: Anthony Villanueva ]
[ June 21, 2002: Message edited by: Anthony Villanueva ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic