1、new Outer().new Inner();
2、static: new Outer.Inner();
3、定义在方法中
1、
1 class Outer { 2 private int age = 24; 3 4 class Inner { 5 void print() { 6 System.out.println(age); 7 } 8 } 9 } 10 11 public class Test { 12 13 public static void main(String[] args) { 14 Outer outer = new Outer(); 15 Outer.Inner inner = outer.new Inner(); 16 inner.print(); 17 } 18 19 }
编译后的文件中有 Outer.class Test.class Outer$Inner.class
2、
1 class Outer { 2 private static int age = 24; 3 4 static class Inner { 5 void print() { 6 System.out.println(age); 7 } 8 } 9 } 10 11 public class Test { 12 13 public static void main(String[] args) { 14 Outer.Inner inner = new Outer.Inner(); 15 inner.print(); 16 } 17 18 }
编译后的文件中有 Outer.class Test.class Outer$Inner.class
3、
1 class Outer { 2 private int age = 24; 3 4 void out(final String name) { 5 class Inner { 6 void print() { 7 System.out.println(name); 8 System.out.println(age); 9 } 10 } 11 new Inner().print(); 12 } 13 14 } 15 16 public class Test { 17 18 public static void main(String[] args) { 19 new Outer().out("crane"); 20 } 21 22 }
注意:传参的话,要用final修饰变量,final String name,否则编译出错。
编译后的文件中有 Outer.class Test.class Outer$Inner.class