01-面向对象(内部类访问规则)

 1 package myFirstCode;
 2 
 3 /*
 4 内部类的访问规则:
 5 1. 内部类可以直接访问外部类的成员,包括私有private。
 6     之所以可以直接访问外部类中的成员,是因为内部类中持有一个外部类的引用,格式 外部类名.this----//Outer.this.x
 7 2. 外部类要访问内部类,必须建立内部类对象。
 8  */
 9 
10 class Outer
11 {
12     private int x = 3;
13      class Inner //内部类
14      {
15          void function()
16          {
17              System.out.println("inner : "+Outer.this.x);//Outer.this.x
18          }
19      }
20      
21      void method()
22      {
23          Inner in = new Inner();
24          in.function();
25      }
26 }
27 
28 public class InnerClassDemo {
29 
30     public static void main(String[] args) {
31 //        Outer out = new Outer();
32 //        out.method();
33         
34         //直接访问内部类中的成员。
35 //        Outer.Inner in = new Outer().new Inner();//面试会问到,实际不会使用
36 //        in.function();
37     }
38 
39 }
View Code

相关文章: