A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© lzw123451 中级黑马   /  2013-2-24 22:52  /  1220 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 李志卫 于 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);                              
       }
   }
}

4 个回复

倒序浏览
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);                              
       }
   }
}
回复 使用道具 举报
付玉光 发表于 2013-2-24 23:09
class Test7
{
    public static void main(String args[])

我的意思是  内部类方法局部变量与外部类属性相同的情况下怎么办, 就是别把那句删了。
回复 使用道具 举报
如果内部类的变量和外部类的成员变量同名,为了区分这两个变量,在调用局部变量的时候用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
                }
        }

}
回复 使用道具 举报
如果是使用内部类的变量,用this.x,如果使用外部类,用out.this.x
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马