Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

My 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.

like image 959
HunderingThooves Avatar asked Aug 25 '11 09:08

HunderingThooves


1 Answers

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);
like image 52
aioobe Avatar answered Sep 19 '22 16:09

aioobe