Java static context
I am using a package that has a method call that is non-static. It will not let me call this method from a static context. I can't change 开发者_运维百科the non-static method, how can I call this method?
Create an object out of that class and call the method on the object?
import com.acme.myclass;
...
MyClass obj = new MyClass();
obj.nonStaticMethod();
If the package you're using has any documentation, be sure to look through it to see how you're expected to use that class and its non-static method. You may also want to read up more on static versus non-static in object-oriented programming in general, to get a better idea of the differences.
In order to call a non-static method, you must call the method on an instance of an object.
Given the following class:
public class MyClass {
public void nonStaticMethod();
}
You would call the method like so:
new MyClass().nonStaticMethod();
Or, if you need to call that method more than once, you can save it into an object.
MyClass instance = new MyClass();
instance.nonStaticMethod();
...
instance.nonStaticMethod();
That method belongs to a class.
So, what you need to do is to create an instance of that class ( most likely with the new operator ) and then use it:
package a;
class A {
public void theMethod(){
}
}
.....
package b;
import a.A;
class Main {
public static void main( String [] args ) {
A a = new A();
a.theMethod();
}
}
You can instantiate an object of the class whenever you need to call the non-static method, with something like:
new BadlyWrittenClass().BadlyWrittenMethod();
However, if you're going to be doing this a lot, it may become inefficient to keep creating and destroying objects in that manner.
A better way may be to instantiate one object, such as in your own class constructor, and just use that any time you need to call the method. Provided it doesn't require a newly initialised object each time, that's likely to be more efficient.
But you may also want to keep in mind that there may be a reason why the method is not static (despite my not-so-subtle jab in the class and method names above). Make sure that it doesn't require some state that you're not setting up when you're creating a new instance. In other words, don't blindly try to do this without understanding.
Static methods don't need to be instantiated whereas instance methods do, inside an instance class.
To get to an instance method you first need an instance of it's class using the new
keyword. You can then access this class' instance methods.
Non-static (instance) cannot be called from static context. Other way is possible.
精彩评论