将一个类定义在另一个类的里面,里面的那个类就叫做内部类(嵌套类,内置类)
内部类的访问规则:
内部类可以直接访问外部类中的成员,包括私有
外部类要访问内部类,必须建立内部类对象
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式: 外部类名.this
访问格式:
1 当内部类定义在外部类的成员位置上,而且非私有,可以在外部其它类中
可以直接建立内部类对象
格式为:
外部类名.内部类名 变量名 = 外部类对象.内部类对象
Outer.Inner in = new Outer().new Inner();
2 当内部类在成员位置上,就可以被成员修饰符所修饰
比如,private:将内部类在外部类中进行封装
static:内部类可以被静态修饰,就具备了静态的特性
当内部类被static修饰后,只能直接访问外部类中的static成员,出现访问局限
在外部其它类中,如何访问内部static内部类的非静态成员呢:new Outer.Inner().function();
在外部其它类中,如何访问内部static内部类的静态成员呢:Outer.Inner.function();
注意:当内部类中定义了静态成员,该内部类必须是static的
当外部类中的静态方法访问内部类时,内部类也必须是静态的
什么时候用内部类:
当描述事物的时候,事物的内部还有事物,该事务用内部类在描述
因为内部事务在使用外部事务的内容
1 classOuter2 {3 private int x = 3;4
5 class Inner//内部类
6 {7 int x = 4;8 static int y = 5;9 voidfunction()10 {11 int x = 6;12 System.out.println("Inner :"+x);//直接访问外部类变量//6
13 System.out.println("Inner :"+this.x);//4
14 System.out.println("Inner :"+Outer.this.x);//4
15 }16 }17
18 static classStaticInner19 {20 voidfunction()21 {22 //System.out.println("Inner :"+x);//invalid 访问局限
23 System.out.println("Inner :"+y)24 }25 }26
27 voidmethod()28 {29 Inner in = new Inner();//外部类访问内部类的方法
30 in.function();31 System.out.println(x);32 }33 }34
35 classInnerClassDemo36 {37 public static voidmain(String[] args)38 {39 Outer out = newOuter();40 //out.method();41 //System.out.println();42 //直接访问内部类中的成员43 //Outer.Inner in = new Outer().new Inner();44 //in.function();
45 newOuter.Inner().function();46 }47 }
内部类定义在局部变量的时候
1 不可以被成员修饰符修饰(static,private之类)
2 可以直接访问外部类中的成员,因为还持有外部类中的引用
但是不可以访问它所在局部中的变量,只能访问被final修饰的局部变量
1 classOuter2 {3 int x = 3;4
5 voidmethod()6 {7 final int y = 4;8 classInner9 {10 voidfunction()11 {12 System.out.println(Outer.this.x);13 System.out.println(y);14 }15 }16 newInner().function();17 }18 }19
20 classInnerClassDemo21 {22 public static voidmain(String[] args)23 {24 newOuter().method();25 }26 }