Nested Classes嵌套类

来源:互联网 发布:心路独舞这个公知 编辑:程序博客网 时间:2024/06/03 12:57

The Java programming language allows you to define a class within another class. Such a class is called anested class and is illustrated here:

class OuterClass {    ...    class NestedClass {        ...    }}

Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declaredstatic are simply called static nested classes. Non-static nested classes are calledinner classes.
class OuterClass {    ...    static class StaticNestedClass {        ...    }    class InnerClass {        ...    }}

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declaredprivate, public, protected, or package private. (Recall that outer classes can only be declaredpublic or package private.)

Why Use Nested Classes?

There are several compelling reasons for using nested classes, among them:

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together.Nesting such "helper classes" makes their package more streamlined.

嵌套类其实就是该顶级类的工具类

Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declaredprivate. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

这句是说,如果A,B都是顶级类,B需要获得A中的成员,那么A中的成员就不能声明为private(破坏了封装性),如果把类B放到A类里,A中的成员就能声明private,而且B可以获得他们。另外,B可以无法让外界获得

More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.

Static Nested Classes

As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

静态类不能直接获取包围他的类的变量或者方法,只能通过对象来用(new 包围他的类.方法())


Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject =     new OuterClass.StaticNestedClass();

Inner Classes

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields.

Also, because an inner class is associated with an instance, it cannot define any static members itself.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass {    ...    class InnerClass {        ...    }}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.The next figure illustrates this idea.

An Instance of InnerClass Exists Within an Instance of OuterClass.

An Instance of InnerClass Exists Within an Instance of OuterClass

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

其实InnerClass就好像是实例的方法或者变量一样,所以要先nstantiate the outer class,然后再 outerObject.new InnerClass();

Additionally, there are two special kinds of inner classes:local classes andanonymous classes.


Note: If you want more information on the taxonomy of the different kinds of classes in the Java programming language (which can be tricky to describe concisely, clearly, and correctly), you might want to read Joseph Darcy's blog:Nested, Inner, Member and Top-Level Classes.

Shadowing

If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declarationshadows the declaration of the enclosing scope. You cannot refer to a shadowed declaration by its name alone. The following example,ShadowTest, demonstrates this:

 public class ShadowTest {    public int x = 0;    class FirstLevel {        public int x = 1;        void methodInFirstLevel(int x) {            System.out.println("x = " + x);            System.out.println("this.x = " + this.x);            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);        }    }    public static void main(String... args) {        ShadowTest st = new ShadowTest();        ShadowTest.FirstLevel fl = st.new FirstLevel();        fl.methodInFirstLevel(23);    }}

The following is the output of this example:

x = 23this.x = 1ShadowTest.this.x = 0

This example defines three variables named x: The member variable of the classShadowTest, the member variable of the inner class FirstLevel, and the parameter in the methodmethodInFirstLevel. The variable x defined as a parameter of the methodmethodInFirstLevel shadows the variable of the inner class FirstLevel. Consequently, when you use the variablex in the method methodInFirstLevel, it refers to the method parameter. To refer to the member variable of the inner classFirstLevel, use the keyword this to represent the enclosing scope:

System.out.println("this.x = " + this.x);

Refer to member variables that enclose larger scopes by the class name to which they belong. For example, the following statement accesses the member variable of the classShadowTest from the method methodInFirstLevel:

System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);参考:http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html