1.java 内部类的同名变量访问
public class Outer { int num=10; //外部类的成员变量 public class Inner{ int num=20; //内部类的成员变量 public void methodInner(){ int num=30; //内部类方法的局部变量 System.out.println(num); System.out.println(this.num); System.out.println(Outer.this.num); //10 } } } public class Main { public static void main(String[] args) { Outer.Inner obj=new Outer().new Inner(); obj.methodInner(); } }输出: 30 20 10
2.局部内部类的定义
public class Outer { public void methodOuter(){ class Inner{ //局部内部类 int num=10; public void methodInner(){ System.out.println(num); } } Inner inner=new Inner(); inner.methodInner(); } } public class Main { public static void main(String[] args) { Outer obj=new Outer(); obj.methodOuter(); //10 } }