- class Outer
- {
- private int x = 3;
- private class Inner //若我加私有的话,怎么访问了?
- {
- int x = 4;
- void function()
- {
- int x = 6;
- System.out.println("Inner Function Variable:"+x);//打印结果为:x=6
- System.out.println("Inner Variable:"+this.x);//内部类成员变量 x = 4
- System.out.println("Outer Variable:"+Outer.this.x);//外部类成员变量 x = 4
- }
- }
- void method()
- {
- //外部类访问内部方式一:
- Inner in = new Inner();
- in.function();
- }
- }
- class InnerClassDemo
- {
- public static void main(String[] args)
- {
- Outer out = new Outer();
- out.method();
- //在主函数中直接访问内部类中的成员
- Outer.Inner oi = new Outer().new Inner();
- oi.function();
- }
- }
复制代码 |