黑马程序员技术交流社区

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

作者: lzw123451    时间: 2013-2-24 22:52
标题: 内部类问题
本帖最后由 李志卫 于 2013-2-25 15:30 编辑

public class Test7
{
    public static void main(String args[])
    {
     new Outer().new Inter().function(55);
     new Outer().Method2(88);
    }
}

class Outer                                                        //外部类
{
      private int x = 0;                              
     private void Method(int x)                     
  {
        System.out.println(x);
   }

    public void Method2(int z)                     
   {
      new Inter().function(z);
   }

     class Inter                                       //内部类
   {
         public void function(int y)             //如果我这里 写int x
       {
              x = y;                                       //那么这里应该怎么写?      内部类方法局部变量与外部类成员变量相冲突的情况  
            // Method(x);                              
       }
   }
}

作者: 付玉光    时间: 2013-2-24 23:09
class Test7
{
    public static void main(String args[])
    {
     new Outer().new Inter().function(55);
     new Outer().Method2(88);
    }
}

class Outer                                                        //外部类
{
     private int x = 0;                              
     private void Method1(int x)                     
  {
        System.out.println(x);
   }

    public void Method2(int z)                     
   {
      new Inter().function(z);
   }

     class Inter                                       //内部类
   {
         public void function(int x)             //我这里 写int x
       {
             Method1(x);                              
       }
   }
}
作者: lzw123451    时间: 2013-2-24 23:12
付玉光 发表于 2013-2-24 23:09
class Test7
{
    public static void main(String args[])

我的意思是  内部类方法局部变量与外部类属性相同的情况下怎么办, 就是别把那句删了。
作者: 胥文    时间: 2013-2-25 09:27
如果内部类的变量和外部类的成员变量同名,为了区分这两个变量,在调用局部变量的时候用this.变量名,在调用外部成员变量的时候用out.this.变量名
eg
public class Outer {
       
        private int x=2;
        class Inner
        {
                int x = 4;
                void function()
                {
                        int x =3;
                        System.out.println(x);//x=3
                        System.out.println(this.x);//x=4
                        System.out.println(Outer.this.x);//x=2
                }
        }

}
作者: 移动小坦克    时间: 2013-2-25 15:28
如果是使用内部类的变量,用this.x,如果使用外部类,用out.this.x




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