I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
Example:
Obj x = new Obj();
x.someMethod();
…or:
Obj.someMethod(); // Is this the static way?
I’m rather confused!
One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.
So in a class
Caryou might have a method:…which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a
Car. But this method (which sets the efficiency of one particularCar):…can’t be static since it’s inconceivable to call the method before any
Carhas been constructed.(By the way, the converse isn’t always true: you might sometimes have a method which involves two
Carobjects, and still want it to be static. E.g.:Although this could be converted to a non-static version, some would argue that since there isn’t a "privileged" choice of which
Caris more important, you shouldn’t force a caller to choose oneCaras the object you’ll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.