Home > DeveloperSection > Forums > Java: where to use static methods
Allen Scott

Total Post:36

Points:254
Posted on    September-04-2015 7:14 AM

 Java Java 
Ratings:


 1 Reply(s)
 380  View(s)
Rate this:
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?

e.g

Obj x = new Obj();
x.someMethod
or

Obj.someMethod
(is this the static way?)

I'm rather confused


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    September-04-2015 7:22 AM

First, ask yourself "does it make sense to call this method, even if no Obj has been constructed yet?" If so, it should definitely be static.

So in a class Car you might have a method double convertMpgToKpl(double mpg) which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But void setMileage(double mpg) (which sets the efficiency of one particular Car) can't be static since it's inconceivable to call the method before any Car has been constructed.

(Btw, the converse isn't always true: you might sometimes have a method which involves two Car objects, and still want it to be static. E.g. Car theMoreEfficientOf( Car c1, Car c2 ). Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.)


Don't want to miss updates? Please click the below button!

Follow MindStick