## Chapter 4. Classes and Interfaces(類和接口)
### Item 24: Favor static member classes over nonstatic(靜態成員類優于非靜態成員類)
A nested class is a class defined within another class. A nested class should exist only to serve its enclosing class. If a nested class would be useful in some other context, then it should be a top-level class. There are four kinds of nested classes: static member classes, nonstatic member classes, anonymous classes, and local classes. All but the first kind are known as inner classes. This item tells you when to use which kind of nested class and why.
嵌套類是在另一個類中定義的類。嵌套類應該只為外部類服務。如果嵌套類在其他環境中有用,那么它應該是頂級類。有四種嵌套類:靜態成員類、非靜態成員類、匿名類和局部類。除了第一種,所有的類都被稱為內部類。本條目會告訴你什么時候使用哪種嵌套類以及原因。
A static member class is the simplest kind of nested class. It is best thought of as an ordinary class that happens to be declared inside another class and has access to all of the enclosing class’s members, even those declared private. A static member class is a static member of its enclosing class and obeys the same accessibility rules as other static members. If it is declared private, it is accessible only within the enclosing class, and so forth.
靜態成員類是最簡單的嵌套類。最好把它看做是一個普通的類,只是碰巧在另一個類中聲明而已,并且可以訪問外部類的所有成員,甚至那些聲明為 private 的成員。靜態成員類是其外部類的靜態成員,并且遵守與其他靜態成員相同的可訪問性規則。如果聲明為私有,則只能在外部類中訪問,等等。
One common use of a static member class is as a public helper class, useful only in conjunction with its outer class. For example, consider an enum describing the operations supported by a calculator (Item 34). The Operation enum should be a public static member class of the Calculator class. Clients of Calculator could then refer to operations using names like Calculator.Operation.PLUS and Calculator.Operation.MINUS.
靜態成員類的一個常見用法是作為公有的輔助類,只有與它的外部類一起使用時才有意義。例如,考慮一個描述了計算器支持的各種操作的枚舉([Item-34](/Chapter-6/Chapter-6-Item-34-Use-enums-instead-of-int-constants.md))。Operation 枚舉應該是 Calculator 類的公有靜態成員類,Calculator 類的客戶端就可以用 `Calculator.Operation.PLUS` 和 `Calculator.Operation.MINUS` 等名稱來引用這些操作。
Syntactically, the only difference between static and nonstatic member classes is that static member classes have the modifier static in their declarations. Despite the syntactic similarity, these two kinds of nested classes are very different. Each instance of a nonstatic member class is implicitly associated with an enclosing instance of its containing class. Within instance methods of a nonstatic member class, you can invoke methods on the enclosing instance or obtain a reference to the enclosing instance using the qualified this construct [JLS, 15.8.4]. If an instance of a nested class can exist in isolation from an instance of its enclosing class, then the nested class must be a static member class: it is impossible to create an instance of a nonstatic member class without an enclosing instance.
從語法上講,靜態成員類和非靜態成員類之間的唯一區別是靜態成員類在其聲明中具有修飾符 static。盡管語法相似,但這兩種嵌套類有很大不同。非靜態成員類的每個實例都隱式地與外部類的外部實例相關聯。在非靜態成員類的實例方法中,你可以調用外部實例上的方法,或者使用受限制的 this 構造獲得對外部實例的引用 [JLS, 15.8.4]。如果嵌套類的實例可以獨立于外部類的實例存在,那么嵌套類必須是靜態成員類:如果沒有外部實例,就不可能創建非靜態成員類的實例。
The association between a nonstatic member class instance and its enclosing instance is established when the member class instance is created and cannot be modified thereafter. Normally, the association is established automatically by invoking a nonstatic member class constructor from within an instance method of the enclosing class. It is possible, though rare, to establish the association manually using the expression enclosingInstance.new MemberClass(args). As you would expect, the association takes up space in the nonstatic member class instance and adds time to its construction.
非靜態成員類實例與外部實例之間的關聯是在創建成員類實例時建立的,之后無法修改。通常,關聯是通過從外部類的實例方法中調用非靜態成員類構造函數自動建立的。使用 `enclosingInstance.new MemberClass(args)` 表達式手動建立關聯是可能的,盡管這種情況很少見。正如你所期望的那樣,關聯占用了非靜態成員類實例中的空間,并為其構造增加了時間。
One common use of a nonstatic member class is to define an Adapter [Gamma95] that allows an instance of the outer class to be viewed as an instance of some unrelated class. For example, implementations of the Map interface typically use nonstatic member classes to implement their collection views, which are returned by Map’s keySet, entrySet, and values methods. Similarly, implementations of the collection interfaces, such as Set and List, typically use nonstatic member classes to implement their iterators:
非靜態成員類的一個常見用法是定義一個 Adapter [Gamma95],它允許外部類的實例被視為某個不相關類的實例。例如,Map 接口的實現通常使用非靜態成員類來實現它們的集合視圖,這些視圖由 Map 的 keySet、entrySet 和 values 方法返回。類似地,集合接口的實現,例如 Set 和 List,通常使用非靜態成員類來實現它們的迭代器:
```
// Typical use of a nonstatic member class
public class MySet<E> extends AbstractSet<E> {
... // Bulk of the class omitted
@Override
public Iterator<E> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<E> {
...
}
}
```
**If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration,** making it a static rather than a nonstatic member class. If you omit this modifier, each instance will have a hidden extraneous reference to its enclosing instance. As previously mentioned, storing this reference takes time and space. More seriously, it can result in the enclosing instance being retained when it would otherwise be eligible for garbage collection (Item 7). The resulting memory leak can be catastrophic. It is often difficult to detect because the reference is invisible.
**如果聲明的成員類不需要訪問外部的實例,那么應始終在聲明中添加 static 修飾符,使其成為靜態的而不是非靜態的成員類。** 如果省略這個修飾符,每個實例都有一個隱藏的對其外部實例的額外引用。如前所述,存儲此引用需要時間和空間。更糟糕的是,它可能會在滿足進行垃圾收集條件時仍保留外部類的實例([Item-7](/Chapter-2/Chapter-2-Item-7-Eliminate-obsolete-object-references.md))。由于引用是不可見的,因此通常很難檢測到。
A common use of private static member classes is to represent components of the object represented by their enclosing class. For example, consider a Map instance, which associates keys with values. Many Map implementations have an internal Entry object for each key-value pair in the map. While each entry is associated with a map, the methods on an entry (getKey, getValue, and setValue) do not need access to the map. Therefore, it would be wasteful to use a nonstatic member class to represent entries: a private static member class is best. If you accidentally omit the static modifier in the entry declaration, the map will still work, but each entry will contain a superfluous reference to the map, which wastes space and time.
私有靜態成員類的一個常見用法是表示由其外部類表示的對象的組件。例如,考慮一個 Map 實例,它將 key 與 value 關聯起來。許多 Map 實現的內部對于映射中的每個 key-value 對都有一個 Entry 對象。雖然每個 entry 都與 Map 關聯,但 entry 上的方法(getKey、getValue 和 setValue)不需要訪問 Map。因此,使用非靜態成員類來表示 entry 是浪費:私有靜態成員類是最好的。如果你不小心在 entry 聲明中省略了靜態修飾符,那么映射仍然可以工作,但是每個 entry 都包含對 Map 的多余引用,這會浪費空間和時間。
It is doubly important to choose correctly between a static and a nonstatic member class if the class in question is a public or protected member of an exported class. In this case, the member class is an exported API element and cannot be changed from a nonstatic to a static member class in a subsequent release without violating backward compatibility.
如果所討論的類是導出類的公共成員或受保護成員,那么在靜態成員類和非靜態成員類之間正確選擇就顯得尤為重要。在本例中,成員類是導出的 API 元素,在后續版本中,不能在不違反向后兼容性的情況下將非靜態成員類更改為靜態成員類。
As you would expect, an anonymous class has no name. It is not a member of its enclosing class. Rather than being declared along with other members, it is simultaneously declared and instantiated at the point of use. Anonymous classes are permitted at any point in the code where an expression is legal. Anonymous classes have enclosing instances if and only if they occur in a nonstatic context. But even if they occur in a static context, they cannot have any static members other than constant variables, which are final primitive or string fields initialized to constant expressions [JLS, 4.12.4].
如你所料,匿名類沒有名稱。它不是外部類的成員。它不是與其他成員一起聲明的,而是在使用時同時聲明和實例化。匿名類可以在代碼中用在任何一個可以用表達式的地方。當且僅當它們出現在非靜態環境中時,匿名類才持有外部類實例。但是,即使它們出現在靜態環境中,它們也不能有除常量(final 修飾的基本類型或者初始化為常量表達式的字符串 [JLS, 4.12.4])以外的任何靜態成員。
There are many limitations on the applicability of anonymous classes. You can’t instantiate them except at the point they’re declared. You can’t perform instanceof tests or do anything else that requires you to name the class. You can’t declare an anonymous class to implement multiple interfaces or to extend a class and implement an interface at the same time. Clients of an anonymous class can’t invoke any members except those it inherits from its supertype. Because anonymous classes occur in the midst of expressions, they must be kept short—about ten lines or fewer—or readability will suffer.
匿名類的使用有很多限制。除非在聲明它們的時候,你不能實例化它們。你不能執行 instanceof 測試,也不能執行任何其他需要命名類的操作。你不能聲明一個匿名類來實現多個接口或擴展一個類并同時實現一個接口。匿名類的使用者除了從超類繼承的成員外,不能調用任何成員。因為匿名類出現在表達式中,所以它們必須保持簡短——大約 10 行或更短,否則會影響可讀性。
Before lambdas were added to Java (Chapter 6), anonymous classes were the preferred means of creating small function objects and process objects on the fly, but lambdas are now preferred (Item 42). Another common use of anonymous classes is in the implementation of static factory methods (see intArrayAsList in Item 20).
在 lambda 表達式被添加到 Java(Chapter 6)之前,匿名類是動態創建小型函數對象和進程對象的首選方法,但 lambda 表達式現在是首選方法([Item-42](/Chapter-7/Chapter-7-Item-42-Prefer-lambdas-to-anonymous-classes.md))。匿名類的另一個常見用法是實現靜態工廠方法(參見 [Item-20](/Chapter-4/Chapter-4-Item-20-Prefer-interfaces-to-abstract-classes.md) 中的 intArrayAsList 類)。
Local classes are the least frequently used of the four kinds of nested classes. A local class can be declared practically anywhere a local variable can be declared and obeys the same scoping rules. Local classes have attributes in common with each of the other kinds of nested classes. Like member classes, they have names and can be used repeatedly. Like anonymous classes, they have enclosing instances only if they are defined in a nonstatic context, and they cannot contain static members. And like anonymous classes, they should be kept short so as not to harm readability.
局部類是四種嵌套類中最不常用的。局部類幾乎可以在任何能夠聲明局部變量的地方使用,并且遵守相同的作用域規則。局部類具有與其他嵌套類相同的屬性。與成員類一樣,它們有名稱,可以重復使用。與匿名類一樣,它們只有在非靜態環境中定義的情況下才具有外部類實例,而且它們不能包含靜態成員。和匿名類一樣,它們應該保持簡短,以免損害可讀性。
To recap, there are four different kinds of nested classes, and each has its place. If a nested class needs to be visible outside of a single method or is too long to fit comfortably inside a method, use a member class. If each instance of a member class needs a reference to its enclosing instance, make it nonstatic; otherwise, make it static. Assuming the class belongs inside a method, if you need to create instances from only one location and there is a preexisting type that characterizes the class, make it an anonymous class; otherwise, make it a local class.
簡單回顧一下,有四種不同類型的嵌套類,每一種都有自己的用途。如果嵌套的類需要在單個方法之外可見,或者太長,不適合放入方法中,則使用成員類。除非成員類的每個實例都需要引用其外部類實例,讓它保持靜態。假設嵌套類屬于方法內部,如果你只需要從一個位置創建實例,并且存在一個能夠描述類的現有類型,那么將其設置為匿名類;否則,將其設置為局部類。
---
**[Back to contents of the chapter(返回章節目錄)](/Chapter-4/Chapter-4-Introduction.md)**
- **Previous Item(上一條目):[Item 23: Prefer class hierarchies to tagged classes(類層次結構優于帶標簽的類)](/Chapter-4/Chapter-4-Item-23-Prefer-class-hierarchies-to-tagged-classes.md)**
- **Next Item(下一條目):[Item 25: Limit source files to a single top level class(源文件僅限有單個頂層類)](/Chapter-4/Chapter-4-Item-25-Limit-source-files-to-a-single-top-level-class.md)**
- Chapter 2. Creating and Destroying Objects(創建和銷毀對象)
- Item 1: Consider static factory methods instead of constructors(考慮以靜態工廠方法代替構造函數)
- Item 2: Consider a builder when faced with many constructor parameters(在面對多個構造函數參數時,請考慮構建器)
- Item 3: Enforce the singleton property with a private constructor or an enum type(使用私有構造函數或枚舉類型實施單例屬性)
- Item 4: Enforce noninstantiability with a private constructor(用私有構造函數實施不可實例化)
- Item 5: Prefer dependency injection to hardwiring resources(依賴注入優于硬連接資源)
- Item 6: Avoid creating unnecessary objects(避免創建不必要的對象)
- Item 7: Eliminate obsolete object references(排除過時的對象引用)
- Item 8: Avoid finalizers and cleaners(避免使用終結器和清除器)
- Item 9: Prefer try with resources to try finally(使用 try-with-resources 優于 try-finally)
- Chapter 3. Methods Common to All Objects(對象的通用方法)
- Item 10: Obey the general contract when overriding equals(覆蓋 equals 方法時應遵守的約定)
- Item 11: Always override hashCode when you override equals(當覆蓋 equals 方法時,總要覆蓋 hashCode 方法)
- Item 12: Always override toString(始終覆蓋 toString 方法)
- Item 13: Override clone judiciously(明智地覆蓋 clone 方法)
- Item 14: Consider implementing Comparable(考慮實現 Comparable 接口)
- Chapter 4. Classes and Interfaces(類和接口)
- Item 15: Minimize the accessibility of classes and members(盡量減少類和成員的可訪問性)
- Item 16: In public classes use accessor methods not public fields(在公共類中,使用訪問器方法,而不是公共字段)
- Item 17: Minimize mutability(減少可變性)
- Item 18: Favor composition over inheritance(優先選擇復合而不是繼承)
- Item 19: Design and document for inheritance or else prohibit it(繼承要設計良好并且具有文檔,否則禁止使用)
- Item 20: Prefer interfaces to abstract classes(接口優于抽象類)
- Item 21: Design interfaces for posterity(為后代設計接口)
- Item 22: Use interfaces only to define types(接口只用于定義類型)
- Item 23: Prefer class hierarchies to tagged classes(類層次結構優于帶標簽的類)
- Item 24: Favor static member classes over nonstatic(靜態成員類優于非靜態成員類)
- Item 25: Limit source files to a single top level class(源文件僅限有單個頂層類)
- Chapter 5. Generics(泛型)
- Item 26: Do not use raw types(不要使用原始類型)
- Item 27: Eliminate unchecked warnings(消除 unchecked 警告)
- Item 28: Prefer lists to arrays(list 優于數組)
- Item 29: Favor generic types(優先使用泛型)
- Item 30: Favor generic methods(優先使用泛型方法)
- Item 31: Use bounded wildcards to increase API flexibility(使用有界通配符增加 API 的靈活性)
- Item 32: Combine generics and varargs judiciously(明智地合用泛型和可變參數)
- Item 33: Consider typesafe heterogeneous containers(考慮類型安全的異構容器)
- Chapter 6. Enums and Annotations(枚舉和注解)
- Item 34: Use enums instead of int constants(用枚舉類型代替 int 常量)
- Item 35: Use instance fields instead of ordinals(使用實例字段替代序數)
- Item 36: Use EnumSet instead of bit fields(用 EnumSet 替代位字段)
- Item 37: Use EnumMap instead of ordinal indexing(使用 EnumMap 替換序數索引)
- Item 38: Emulate extensible enums with interfaces(使用接口模擬可擴展枚舉)
- Item 39: Prefer annotations to naming patterns(注解優于命名模式)
- Item 40: Consistently use the Override annotation(堅持使用 @Override 注解)
- Item 41: Use marker interfaces to define types(使用標記接口定義類型)
- Chapter 7. Lambdas and Streams(λ 表達式和流)
- Item 42: Prefer lambdas to anonymous classes(λ 表達式優于匿名類)
- Item 43: Prefer method references to lambdas(方法引用優于 λ 表達式)
- Item 44: Favor the use of standard functional interfaces(優先使用標準函數式接口)
- Item 45: Use streams judiciously(明智地使用流)
- Item 46: Prefer side effect free functions in streams(在流中使用無副作用的函數)
- Item 47: Prefer Collection to Stream as a return type(優先選擇 Collection 而不是流作為返回類型)
- Item 48: Use caution when making streams parallel(謹慎使用并行流)
- Chapter 8. Methods(方法)
- Item 49: Check parameters for validity(檢查參數的有效性)
- Item 50: Make defensive copies when needed(在需要時制作防御性副本)
- Item 51: Design method signatures carefully(仔細設計方法簽名)
- Item 52: Use overloading judiciously(明智地使用重載)
- Item 53: Use varargs judiciously(明智地使用可變參數)
- Item 54: Return empty collections or arrays, not nulls(返回空集合或數組,而不是 null)
- Item 55: Return optionals judiciously(明智地的返回 Optional)
- Item 56: Write doc comments for all exposed API elements(為所有公開的 API 元素編寫文檔注釋)
- Chapter 9. General Programming(通用程序設計)
- Item 57: Minimize the scope of local variables(將局部變量的作用域最小化)
- Item 58: Prefer for-each loops to traditional for loops(for-each 循環優于傳統的 for 循環)
- Item 59: Know and use the libraries(了解并使用庫)
- Item 60: Avoid float and double if exact answers are required(若需要精確答案就應避免使用 float 和 double 類型)
- Item 61: Prefer primitive types to boxed primitives(基本數據類型優于包裝類)
- Item 62: Avoid strings where other types are more appropriate(其他類型更合適時應避免使用字符串)
- Item 63: Beware the performance of string concatenation(當心字符串連接引起的性能問題)
- Item 64: Refer to objects by their interfaces(通過接口引用對象)
- Item 65: Prefer interfaces to reflection(接口優于反射)
- Item 66: Use native methods judiciously(明智地使用本地方法)
- Item 67: Optimize judiciously(明智地進行優化)
- Item 68: Adhere to generally accepted naming conventions(遵守被廣泛認可的命名約定)
- Chapter 10. Exceptions(異常)
- Item 69: Use exceptions only for exceptional conditions(僅在確有異常條件下使用異常)
- Item 70: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors(對可恢復情況使用 checked 異常,對編程錯誤使用運行時異常)
- Item 71: Avoid unnecessary use of checked exceptions(避免不必要地使用 checked 異常)
- Item 72: Favor the use of standard exceptions(鼓勵復用標準異常)
- Item 73: Throw exceptions appropriate to the abstraction(拋出能用抽象解釋的異常)
- Item 74: Document all exceptions thrown by each method(為每個方法記錄會拋出的所有異常)
- Item 75: Include failure capture information in detail messages(異常詳細消息中應包含捕獲失敗的信息)
- Item 76: Strive for failure atomicity(盡力保證故障原子性)
- Item 77: Don’t ignore exceptions(不要忽略異常)
- Chapter 11. Concurrency(并發)
- Item 78: Synchronize access to shared mutable data(對共享可變數據的同步訪問)
- Item 79: Avoid excessive synchronization(避免過度同步)
- Item 80: Prefer executors, tasks, and streams to threads(Executor、task、流優于直接使用線程)
- Item 81: Prefer concurrency utilities to wait and notify(并發實用工具優于 wait 和 notify)
- Item 82: Document thread safety(文檔應包含線程安全屬性)
- Item 83: Use lazy initialization judiciously(明智地使用延遲初始化)
- Item 84: Don’t depend on the thread scheduler(不要依賴線程調度器)
- Chapter 12. Serialization(序列化)
- Item 85: Prefer alternatives to Java serialization(優先選擇 Java 序列化的替代方案)
- Item 86: Implement Serializable with great caution(非常謹慎地實現 Serializable)
- Item 87: Consider using a custom serialized form(考慮使用自定義序列化形式)
- Item 88: Write readObject methods defensively(防御性地編寫 readObject 方法)
- Item 89: For instance control, prefer enum types to readResolve(對于實例控制,枚舉類型優于 readResolve)
- Item 90: Consider serialization proxies instead of serialized instances(考慮以序列化代理代替序列化實例)