public class Main {
void sum(int a, int b) {
int c = a + b;
System.out.println(c);
}
public static void main(String args[]) {
Main ob = new Main();
ob.sum(10, 125);
}
}
In the above code there is no instance variable, but I have read that if a method is an instance method it should access instance variable. So is 'sum' an instance method?
sum
is an instance method here, because it's not static
and requires an instance of the object. You create your instance here:
Main ob = new Main();
In this particular case sum
could indeed be made static
, slightly simplifying the code by not requiring an instance.
I have read that if a method is an instance method it should access instance variable
I suspect what you were reading is suggesting that if a method doesn't interact with the instance at all then it probably should be static
. There may be mention of the term "pure function" in the text somewhere.
I wouldn't go so far as to say that all potentially static
methods everywhere should be made static
as a universal rule. It really comes down to the semantics of the object itself. Since the object you have here has very little semantic context, this one tiny example could easily go either way.
But suppose you expanded your object to also include methods for subtract
, multiply
, divide
, etc. As the object expands, suppose one or more of those additional methods did use instance variables. It would be a jarring experience to have an object with multiple semantically-similar methods, some of which are static
and some of which are not.
Rather than focus on any particular rule that someone gives you, focus on what you are intending to build as your object. If you think that it should be static
, make it as such. If you feel that it shouldn't, then don't. If you're unsure, then as an exercise implement both and see which you prefer in that particular case.
Looking to the future plans for what you're intending to build is important, because the more code you have relying on your object throughout the application the harder it will be to change from static
to instance or vice-versa.