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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With