Java内部类2:Java实例内部类

实例内部类指没有用 static 修饰的内部类。示例代码如下:

  1. public class Outer
  2. {
  3. class Inner
  4. {
  5. //实例内部类
  6. }
  7. }


上述示例中的 Inner 类就是实例内部类。实例内部类有如下特点。

(1) 在外部类的静态方法和外部类以外的其他类中,必须通过外部类的实例创建内部类的实例

  1. public class Outer
  2. {
  3. class Inner1{}
  4. Inner1 i=new Inner1(); //不需要创建外部类实例
  5. public void method1()
  6. {
  7. Inner1 i=new Inner1(); //不需要创建外部类实例
  8. }
  9. public static void method2()
  10. {
  11. Inner1 i=new Outer().new inner1(); //需要创建外部类实例
  12. }
  13. class Inner2
  14. {
  15. Inner1 i=new Inner1(); //不需要创建外部类实例
  16. }
  17. }
  18. class OtherClass
  19. {
  20. Outer.Inner i=new Outer().new Inner(); //需要创建外部类实例
  21. }


(2) 在实例内部类中,可以访问外部类的所有成员

  1. public class Outer
  2. {
  3. public int a=100;
  4. static int b=100;
  5. final int c=100;
  6. private int d=100;
  7. public String method1()
  8. {
  9. return "实例方法1";
  10. }
  11. public static String method2()
  12. {
  13. return "静态方法2";
  14. }
  15. class Inner
  16. {
  17. int a2=a+1; //访问public的a
  18. int b2=b+1; //访问static的b
  19. int c2=c+1; //访问final的c
  20. int d2=d+1; //访问private的d
  21. String str1=method1(); //访问实例方法method1
  22. String str2=method2(); //访问静态方法method2
  23. }
  24. public static void main(String[] args)
  25. {
  26. Inner i=new Outer().new Inner(); //创建内部类实例
  27. System.out.println(i.a2); //输出101
  28. System.out.println(i.b2); //输出101
  29. System.out.println(i.c2); //输出101
  30. System.out.println(i.d2); //输出101
  31. System.out.println(i.strl); //输出实例方法1
  32. System.out.println(i.str2); //输出静态方法2
  33. }
  34. }

提示:如果有多层嵌套,则内部类可以访问所有外部类的成员

(3) 在外部类中不能直接访问内部类的成员,而必须通过内部类的实例去访问。如果类 A 包含内部类 B,类 B 中包含内部类 C,则在类 A 中不能直接访问类 C,而应该通过类 B 的实例去访问类 C

(4) 外部类实例与内部类实例是一对多的关系,也就是说一个内部类实例只对应一个外部类实例,而一个外部类实例则可以对应多个内部类实例

如果实例内部类 B 与外部类 A 包含有同名的成员 t,则在类 B 中 t 和 this.t 都表示 B 中的成员 t,而 A.this.t 表示 A 中的成员 t。

  1. public class Outer
  2. {
  3. int a=10;
  4. class Inner
  5. {
  6. int a=20;
  7. int b1=a;
  8. int b2=this.a;
  9. int b3=Outer.this.a;
  10. }
  11. public static void main(String[] args)
  12. {
  13. Inner i=new Outer().new Inner();
  14. System.out.println(i.b1); //输出20
  15. System.out.println(i.b2); //输出20
  16. System.out.println(i.b3); //输出10
  17. }
  18. }


(5) 在实例内部类中不能定义 static 成员,除非同时使用 final 和 static 修饰

猜你喜欢

转载自blog.csdn.net/weixin_44015669/article/details/90114993