开发者

accessing non-static method from static context

I'm a little confused about this, and my browsing through the suggested answers on here didn't yield an immediate result that worked in my context.

M开发者_高级运维y question is basic. let's assume that I have a method that is something like this.

private int someFunction(int x, int y){
    return (x+y+5)
} 

but I would like to call this function from main (public static void main(String args[]) ). How would I go about doing that?

If there is a tutorial you'd think would help me in this case I would greatly appreciate that too.


This function doesn't require access to any member-variables, so you could declare the method as static:

private static int someFunction(int x, int y) {
        ^^^^^^
    return (x+y+5)
} 

This would allow you to call it from main, using either someFunction(arg1, arg2) or YourClass.someFunction(arg1, arg2).


If the method actually do need access to member variables (and/or the this reference) you can't declare the method as static. In that case you'll have to create an instance of the class that contains the method in order to call it:

new YourClass().someFunction(0, 1);

or (if you need to reuse the instance later)

YourClass x = new YourClass();
x.sumFunction(0, 1);


You need to have an instance of the class that particular method belongs to call an instance method.

In your case,

new MyClass().someFunction(5,6);


You have to create instance first. The instance method (method that is not static) cannot be accessed from static context by definition.

So, if for example you have class MyApp that contains someFunction() and main(String[] args) do the following in your main method:

new MyApp().someFunction(1, 2);


Basically, you can only call non-static methods from objects [instances of a class] rather than the class itself.

check out the Sun java tutorials for an explanation of the difference between objects and classes if you're a bit confused - it's a very important concept!

you could either make the function static if it doesn't reference any local variables, or create an instance of the class to be able to call it locally.


Since your method someFunction is not static you will not be able to call this method from a static context i:e main(). 1. So you can make someFunction

static private someFunction () 

2.or can create an object from main() and call someFunction like :

A a = new A();
a.someFunction(4, 5);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜