File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Instance methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Instance methods" Watch "Instance methods" New topic
Author

Instance methods

Armstrong D
Greenhorn

Joined: Apr 16, 2002
Posts: 7
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

Joined: Aug 26, 2001
Posts: 7610
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...


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Instance methods