This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static method calls to nonstatic  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 "static method calls to nonstatic  methods" Watch "static method calls to nonstatic  methods" New topic
Author

static method calls to nonstatic methods

Olga Logan
Greenhorn

Joined: Oct 09, 2003
Posts: 6
Hello,
I just got confused.... I have created a static method and called nonstatic method inside of it and it compiled.
Here is an example:
class A{
public final return getMethod(){
return 1;
}
}
class B {
public static A atest;
public static void testMethod(){
atest = new A();
atest.getMethod();
}
}
Why did it work?
Thanks,
Olga
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
In order to invoke an instance method (non-static), you need to have an instance of the object to invoke the instance upon. You have that. You created an A object and referenced it with the variable atest. Now that you have that object, you are free to invoke any methods on it you want, static or not, no matter what context you are in, static or not.
I think the error you were expecting would be better illustrated by this:

I hope that helps,
Corey


SCJP Tipline, etc.
Olga Logan
Greenhorn

Joined: Oct 09, 2003
Posts: 6
Thank you. It did help:-)
 
Have you checked out Aspose?
 
subject: static method calls to nonstatic methods
 
jQuery in Action, 3rd edition