(本文参考:http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html)
class OuterClass { ...... class StaticNestedClass { ...... } ...... class InnerClass { ...... }
nested classes (嵌套类)分为两种:non-static与static,前者通常称作inner classes,后者称作static nested classes。
两种nested classes都是其enclosing class的内部成员,non-static classes可以引用到包装类的private成员,static classes没有这个能力。两种nested classes都可以被声明为public/protected/private/package private。
OuterClass.StaticNestedClass foo = new OuterClass.StaticNestedClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
原文用一段很简洁的代码讲清了这个问题
public class Main { public static void main(String[] args) throws Exception { (new OuterClass()).new InnerClass().printX(2); System.out.println("FINISH!"); } } class OuterClass { int x = 0; class InnerClass { int x = 1; public void printX (int x) { System.out.println("x=" + x); System.out.println("this.x=" + this.x); System.out.println("OuterClass.this.x=" + OuterClass.this.x); } } }
输出:
x=2 this.x=1 OuterClass.this.x=0 FINISH!
原文:http://www.cnblogs.com/maozhige/p/4063596.html