何时使用静态方法 [英] When to use static methods
问题描述
我想知道什么时候使用静态方法?假设我有一个带有一些 getter 和 setter 的类、一两个方法,并且我希望这些方法只能在类的实例对象上调用.这是否意味着我应该使用静态方法?
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?
示例:
Obj x = new Obj();
x.someMethod();
...或:
Obj.someMethod(); // Is this the static way?
我有点困惑!
推荐答案
一个经验法则:问问自己即使尚未构造任何对象,调用此方法是否有意义?";如果是这样,它肯定应该是静态的.
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.
所以在 Car
类中你可能有一个方法:
So in a class Car
you might have a method:
double convertMpgToKpl(double mpg)
...这将是静态的,因为人们可能想知道 35mpg 转换成什么,即使没有人制造过 Car
.但是这个方法(它设置了一个特定Car
的效率):
...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 particular Car
):
void setMileage(double mpg)
...不能是静态的,因为在构造任何 Car
之前调用该方法是不可思议的.
...can't be static since it's inconceivable to call the method before any Car
has been constructed.
(顺便说一句,反过来并不总是正确的:您有时可能有一个涉及两个 Car
对象的方法,并且仍然希望它是静态的.例如:
(By the way, 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)
虽然这可以转换为非静态版本,但有些人会争辩说,因为没有特权"版本.选择哪个 Car
更重要,你不应该强迫调用者选择一个 Car
作为你调用方法的对象.不过,这种情况只占所有静态方法的一小部分.
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.
这篇关于何时使用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!