2013-03-13 71 views

回答

3

當你不需要他們知道類狀態來處理某些東西時,方法是靜態的。輔助方法就是這種情況的很好例子。

DateUtils.getDateNowInGMT() 

上面的方法並不需要任何狀態給你一個答案。下面的一個。

Withdrawer w = new Withdrawer.Builder().account(12545).build(); 
w.withdraw(100); 

如果您不知道帳戶號碼(與提款人相關的帳戶號碼),您將無法提取()款項。您當然可以認爲這可能是一種靜態方法,並且將帳戶信息傳遞給該方法可以解決問題,但由於所有其他方法都需要相同的帳戶信息,因此會造成不便。

+0

+1好樣品。 – 2013-03-13 05:15:07

0

是的。

這是正確的方法,至少我遵循。

例如,實用方法應該是靜態的。

但是,大多數未來需求和改變都需要很多,我們今天也不能預見所有這些需求。所以實例應優於static。直到除非你遵循某種設計模式。

1

一般來說它會更困難,爲您單位,如果你使用了大量的靜態方法(人們認爲它更容易使用的東西嘲笑的對象像Mockito不是嘲笑使用的東西一個靜態方法類似Powermock)測試代碼。

但是,如果你不關心這一點,並且該方法不使用它所在類的實例數據,那麼也可以將它靜態化。

0

因此您可以使用任何類型的實現。但不是可能性,標準應該是要求。 如果你有一些操作要在類中執行,你應該選擇靜態方法。例如,如果您必須爲每個實例生成一個uniqueID,或者您必須初始化實例將使用的任何內容,如顯示或db-driver。在其他情況下,在操作是特定於實例的情況下,優選實例方法。

0

只有當靜態方法有意義時,方法才應該是靜態的。靜態方法屬於類而不屬於它的特定實例。靜態方法只能使用該類的其他靜態功能。例如,靜態方法無法調用實例方法或訪問實例變量。如果這對你正在設計的方法有意義,那麼使用靜態是一個好主意。

靜態元素,無論是變量還是方法,都會在類加載時加載到內存中,並一直保留到執行結束或類加載器卸載/重新加載它所屬的類。

我使用靜態方法,當他們的計算不適合我的應用程序的一般面向對象建模。通常,諸如驗證輸入數據或保存特定於整個應用程序執行的信息或訪問外部數據庫的方法等實用方法都是很好的選擇。

0

據我所知, 如果你有這樣一種代碼或邏輯來利用或產生與特定對象狀態有關的東西,或者簡單地說,如果你的邏輯在方法中用不同的對象來處理不同的對象輸入並生成一些不同的輸出集合,則需要將此方法作爲實例方法。 另一方面,如果你的方法有一個對每個對象都是通用的邏輯,並且輸入和輸出不取決於對象的狀態,你應該聲明它是靜態的,但不是實例。

Explaination with examples: 

    Suppose you are organizing a college party and you have to provide a common coupon to the students of all departments,you just need to appoint a person for distributing a common coupon to students(without knowing about his/her department and roll no.) as he/she(person) approaches to the coupon counter. 
    Now think if you want to give the coupons with different serial numbers according to the departments and roll number of students, the person appointed by you need to get the department name and roll number of student(as input from each and every student) 
    and according to his/her department and roll number he will create a separate coupon with unique serial number. 

First case is an example where we need static method, if we take it as instance method unnecessary it will increase the burden. 

Second case is an example of instance method, where you need to treat each student(in sense of object) separately. 

這個例子可能看起來很愚蠢,但我希望它能幫助你明確地理解這個區別。

相關問題