黑马程序员技术交流社区

标题: java内部类 [打印本页]

作者: viliv715    时间: 2014-8-25 09:18
标题: java内部类
本帖最后由 viliv715 于 2014-8-26 18:01 编辑
  1. /*
  2. 内部类:
  3. a内部类可以直接访问外部类中的成员,包括私有成员.之所以可以访问外部类的成员
  4.         是因为内部类中持有了一个外部类的引用,格式:外部类名.this
  5. b外部类要访问内部类中的成员必须要建立内部类的对象

  6. 访问格式:
  7. a当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中直接建立内部类对象。
  8. 格式:
  9.         外部类名.内部类名 变量名 = 外部类对象.内部类对象
  10.         Outer.Inner in = new Outer().Inner();
  11. b当内部类在成员位置上,就可以被成员修饰符修饰。
  12.         private:将内部类在外部类进行封装。
  13.         static:内部类就据别static的特征。当内部类被static修饰后,
  14.                         只能直接访问外部类中的static成员,出现了访问局限。
  15.                         注意:
  16.                         当内部类出现了静态成员,内部类也必须是静态的。
  17.                         当外部类中的静态方法访问内部类时,内部类也必须是静态的。
  18.                         外部其他类直接访问静态内部类的非静态成员
  19.                         new  Outer().Inner().function();
  20.                         外部其他类直接访问静态内部类的静态成员
  21.                         Outer().Inner().function();
  22. c内部类定义在局部时:
  23.         不可以被成员修饰符修饰
  24.         可以直接访问外部类中的成员,因为还持有外部类中的引用、
  25.         不可以访问它所在局部中的变量,只能访问被final修饰的局部变量。
  26. */
  27. class Outer{
  28.         private int x = 3;
  29.         //内部类
  30.         class Inner{
  31.                 int x = 4;
  32.                 void function()
  33.                 {
  34.                         int x = 5;
  35.                         //x=5
  36.                         System.out.println("Inner:" + x);
  37.                         //x=4
  38.                         System.out.println("Inner:" + this.x);
  39.                         //x=3
  40.                         System.out.println("Inner:" + Outer.this.x);
  41.                 }
  42.         }

  43.         void method(){
  44.                 Inner in = new Inner();
  45.                 in.function();
  46.         }
  47. }

  48. class InnerClassDemo{
  49.         public static void main(string[] args){
  50.                 Outer out = new Outer();
  51.                 out.method();

  52.                 //直接访问内部类成员
  53.                 Outer.Inner in = new Outer().Inner();
  54.                 in.function();
  55.         }
  56. }
复制代码



作者: abc83983682    时间: 2014-8-25 09:26
总结的蛮到位的!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2