内部类:
①静态内部类中可以有非静态的方法
②当内部类中有静态方法或者静态成员变量时,一定是静态内部类
一般内部类在外部类的成员变量位置,像这样:
1 public classOuter {2 classInner{3
4 }5 }
1、外部类访问内部类:
内部类被static修饰:可以直接new
Inner in = new Inner();
内部类没有被static修饰:得先new出来外部类的实例,再new内部类的
Inner in = new Outer().new Inner();
2、内部类访问外部类:(外部类.this.变量)
1 public classOuter {2 int x = 9;3 classInner{4 int x = 8;5 public voidtest(){6 int x = 7;7 System.out.println(x);8 System.out.println(this.x);9 System.out.println(Outer.this.x);10 test1();11 }12 }13
14 private voidtest1(){15 System.out.println("test");16 }17 public static voidmain(String[] args) {18 Inner in = new Outer().newInner();19 in.test();20 }21 }
输出为:7,8,9,test
分析:第七行第八行相信大家都没有什么问题,第九行输出的是9,说明访问到了外部类的变量ÿ