Does declaring a method as static have any advantage except that it can be called without instantiating a class?
问题:
回答1:
Not needing to instantiate a class to call a method can be an advantage in itself. Consider libraries of methods, such as java.lang.Math.
Static methods are also used as factory methods -- you call a static method to get an object -- usually an implementation of some interface. The idea is that the method can figure out which specific implementation to build for you given the parameters you pass it. If you had to have an object instance before you could call such a method you'd either have a chicken-and-egg or would be creating instances of a second class just to call a factory method to give you instances of the first.
You might also find this StackOverflow question on whether or not methods should be static by default of interest, especially the accepted answer.
回答2:
There are many reasons to use static
methods. Here are a few examples:
- Setting a parameter that is relevant for each instance of the class, such as format of time (24-hours vs. AM/PM) when you have many clocks.
- Provide a single operation (such as Math class, as QuantumMechanic mentioned) that is not related to something bigger / other data.
- Restrict the use of one instance (singleton), and provide manipulation to it from different places.
Most of all, even when you program OO, it doesn't mean that every single thing is an object, and every method need to be called on an object, some methods are independent, and forcing OO patterns on them seems to me like a bad practice. I don't remember even one application that I wrote that didn't have some use of static methods.
回答3:
I don't think of static methods exactly as an advantage - I guess necessary evil is much more appropriated.
When one designs a class, sometimes s/he will get to a point where there is no other natural option but declaring a static method. The canonical example is coding an instance counter, when you need to keep track of all instances of a class: the obvious way of doing that would be declaring a static private counter, and a public static getter method.
Static methods are also handy when dealing with functionality not "object oriented" by nature: helper methods and multi-purpose libraries are usually declared as static. Still, many times this is a symptom of bad design - these so called "generic" methods could probably be encapsulated inside real objects with a little more thought, so you should be careful when taking that kind of decision.
So keep in mind that static is just global in disguise, and that hurts the very foundations of object oriented programming. In fact some OO languages completely lack static declarations for that reason (Scala for instance uses companion singletons for the same purpose of static methods).