+ 4
Java : How do you choose to use static vs non static methods in your project?
5 ответов
+ 12
Static methods are used when we do not want to create an object to have to use the method. Because a method does not always require an object to perform a task, an example is the methods of the Math class. Another example is the main method because jvm does not create an object to run the program, that would not make sense. Another context for using static methods is when you have to call a method from a static method. Static methods can only call other static methods.
+ 5
in this specific case of which car to choose (objects) they are being passed as an argument to a static method(this is perfectly valid) . But a static method could never be called from a created object.
+ 4
Yes, static method is bound to class instead to object of class. So it should be invoked like classname.methodname
In arguments, anything could be passed be it variables or objects.
+ 3
One rule-of-thumb: 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.)
Found the above answer on static overflow: https://stackoverflow.com/questions/2671496/java-when-to-use-static-methods
0
Use instance methods whenever you can.
Static is good for factory methods, but a workaround most everywhere else.