<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                ## 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)**
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看