問題:什么時候使用靜態方法
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?
我想知道什么時候使用靜態方法?就是說我有一個 帶有一些getter和setter方法的類,我想這些只在一個類的實例對象中使用。那是不是意味著我應該用一個靜態方法
例如:
Obj x = new Obj();
x.someMethod();
...or:Obj.someMethod(); // Is this the static way?
我現在非常疑惑
回答一
一條經驗法則,問你自己“調用這個方法是否有意義的,即使還沒有對象被構造出來” 如果是的話,他應該被定義為靜態的。
就像在你一個汽車類里面,可能有一個方法
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 this method (which sets the efficiency of one particular Car):
這個方法可以是靜態的,因為即使沒有建造過一輛汽車,我們也想知道35mpg 可以轉換成多少。
但是下面這個方法(用來設置一輛特定汽車的功率)
void setMileage(double mpg)
這個就不能成為靜態的了,因為在車輛沒有被構造之前,不可能調用這個方法,
順便說一下,這個轉換不一定是對的,你有時可能有一個方法去調用兩臺汽車對象,這時候就還是靜態的了,例如:
Car theMoreEfficientOf(Car c1, Car c2)
雖然它可以被轉換成非靜態的版本,一些人可能就會爭論因為不存在一個特權選擇哪臺車比較重要,你不能強制選擇一臺車去調用這個方法。但是這種情況只是占所有靜態方法中一個很小的部分
文章翻譯自Stack Overflow:https://stackoverflow.com/questions/2671496/when-to-use-static-methods