黑马程序员技术交流社区

标题: 内部类引用外部类的成员变量 [打印本页]

作者: 不愿一人    时间: 2013-12-22 16:23
标题: 内部类引用外部类的成员变量
其他地方不给回复,还是来着吧,求大神指点啊
这是我在黑马做基础测试时遇到的,对于func中的x直接访问就可以
对于B类中的成员变量x,用this.x
但对A类中的成员变量,应该怎么访问啊



作者: 刘旭升    时间: 2013-12-22 18:26
你看看这两句话对你有没有帮助:内部类可以直接调用外嵌类的方法和成员变量。其中外嵌类把内部类的对象看成是自己的成员,貌似你上面的程序没有调用呢。
作者: 天天学习    时间: 2013-12-22 18:46
  1. class Outer
  2. {
  3.         private int x = 3;
  4.         class Inner
  5.         {
  6.                 private int x  = 4;
  7.                 void function()
  8.                 {
  9.                         int x = 5;
  10.                         System.out.println("x="+x);
  11.                         System.out.println("tis.x="+this.x);
  12.                         System.out.println("Outer.this.x="+Outer.this.x);
  13.                 }
  14.         }
  15. }
  16. class InnerClass
  17. {
  18.        
  19.         public static void main(String[] args)
  20.         {
  21.                 Outer.Inner in = new Outer().new Inner();
  22.                 in.function();
  23.         }
  24. }
复制代码

打印结果为: x=5,this.x=4,Outer.this.x=3;由此可知:x为内部类局部变量,this.x为内部类成员变量而Outer.this.x为外部类成员变量
           




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