Ray's playground

 

Inner Classes(Thinking in Java)

  If you want to make an object of the inner class anywhere except from within a non-static method of the outer class, you must specify the type of that object as OuterClassName.InnerClassName,

  So an inner class has automatic access to the members of the enclosing class. How can this happen? The inner class secretly captures a reference to the particular object of the enclosing class that was responsible for creating it. Then, when you refer to a member of the enclosing class, that reference is used to select that member.

  If you need to produce the reference to the outer-class object, you name the outer class followed by a dot and this. The resulting reference is automatically the correct type, which is known and checked at compile time, so there is no runtime overhead. Sometimes you want to tell some other object to create an object of one of its inner classes. To do this you must provide a reference to the other outer-class object in the new expression, using the .new syntax.

  Inner classes can be created within a method or even an arbitrary scope. There are two reasons for doing this:

  1.As shown previously, you’re implementing an interface of some kind so that you can create and return a reference.

  2.You’re solving a complicated problem and you want to create a class to aid in your solution, but you don’t want it publicly available. 

  If you don’t need a connection between the inner-class object and the outerclass object, then you can make the inner class static. This is commonly called a nested class.2 To understand the meaning of static when applied to inner classes, you must remember that the object of an ordinary inner class implicitly keeps a reference to the object of the enclosing class that created it. This is not true, however, when you say an inner class is static. A nested class means:

  1.You don’t need an outer-class object in order to create an object of a nested class.

  2.You can’t access a non-static outer-class object from an object of a nested class.

Nested classes are different from ordinary inner classes in another way, as well. Fields and methods in ordinary inner classes can only be at the outer level of a class, so ordinary inner classes cannot have static data, static fields, or nested classes. However, nested classes can have all of these.

posted on 2010-01-26 22:02  Ray Z  阅读(320)  评论(0编辑  收藏  举报

导航