wood burning stoves 2.0*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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:-)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static method calls to nonstatic methods
 
Similar Threads
Polymorphic Synchronized methods
calling bean method in servlet
A quick question on threads
non-static variable cl cannot be referenced from a static context
Can we override Static Methods