每次同時使用 static 跟 final 的時候,都會忘記到底是 static 先還是 final 先。工作的時候,因為公司內部有工具可以統一 code style,所以就沒有太糾結這個問題。但在自己的 side projects 上,常常會忘記到底是哪個順序比較合適,也比較符合大家的習慣。
找了一些網路資料,發現有相關的資源建議修飾詞 (modifier) 的使用順序。因為經常記不住,所以就乾脆寫了這篇把這些資源記下來,以後方便查找。
首先第一個,這是 Google 提供的 Java Style Guide。在 4.8.7 Modifiers 裡有提到:
Class and member modifiers, when present, appear in the order recommended by the Java Language Specification:
public protected private abstract default static final transient volatile synchronized native strictfp
另外在 OpenJDK 社群裡也有類似的 Java Style Guidelines。在 Modifiers 裡也有提到:
Modifiers should go in the following order
1. Access modifier (public / private / protected)
2. abstract
3. static
4. final
5. transient
6. volatile
7. default
8. synchronized
9. native
10. strictfp