`
leonzhx
  • 浏览: 793929 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 22: Favor static member classes over nonstatic

阅读更多

1.  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.

 

2.  There are four kinds of nested classes: static member classes, nonstatic member classes, anonymous classes, and local classes.

 

3.  A static member class 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. It’s a static member of its enclosing class and obeys the same accessibility rules as other static members. One common use of a static member class is as a public helper class, useful only in conjunction with its outer class. (i.e. The Operation enum should be a public static member class of the Calculator class.)

 

4.  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. 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.

 

5.  One common use of a nonstatic member class is to define an Adapter 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.

 

6.  If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration. If you omit this modifier, each instance will have an extraneous reference to its enclosing instance. Storing this reference costs time and space, and can result in the enclosing instance being retained when it would otherwise be eligible for garbage collection.

 

7.  A common use of private static member classes is to represent components of the object represented by their enclosing class. (i.e. Map.Entry)

 

8.  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. One common use of anonymous classes is to create function objects (Item 21) on the fly.

 

9.  Local classes have enclosing instances only if they are defined in a nonstatic context, and they cannot contain static members.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics