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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杨千里 中级黑马   /  2012-9-15 01:51  /  1134 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 杨千里 于 2012-9-15 13:20 编辑

public class Example{
         String str=new String("good");            
         char[] ch = {'a','b','c'};                       
         public void change(String str,char ch[])
        {            
          str="test ok";
          ch[0]='g';
        }

         public static void main(String args[])
        {
          Example ex=new Example();            
          ex.change(ex.str,ex.ch);         //调用change()方法      
          System.out.print(ex.str+" and ");
          Sytem.out.print(ex.ch);
      }
}

结果不应该是   test ok   and gbc  吗?  但为什么结果是good and gbc  ? 搞了半天弄 不明白,请解释  谢谢

评分

参与人数 1技术分 +1 收起 理由
唐志兵 + 1 赞一个!

查看全部评分

2 个回复

倒序浏览
public class Example{
    String str=new String("good");            
     char[] ch = {'a','b','c'};                       
     public void change(String str,char ch[])
    {            
     this.str="test ok"; //这样就行了,this.str调用的是外面的str,这里是把外面的引用str,指向了“test ok”
                              //str=“test ok”;这里的str    是change(String str,char ch[]))函数中的str,是形参,只是在函数里有用,出了函数就拜拜了

     ch[0]='g';
   }
    public static void main(String args[])
    {
     Example ex=new Example();            
      ex.change(ex.str,ex.ch);         //调用change()方法      
      System.out.print(ex.str+" and ");
     System.out.print(ex.ch);
}
}
回复 使用道具 举报
你没理解成员变量和局部变量。
作用范围。
成员变量作用于整个类中。
局部变量变量作用于函数中,或者语句中。
在内存中的位置:
成员变量:在堆内存中,因为对象的存在,才在内存中存在。
局部变量:存在this:看上去,是用于区分局部变量和成员变量同名情况。

this:是用于区分局部变量和成员变量同名情况。
this代表它所在函数所属对象的引用。
简单说:哪个对象在调用this所在的函数,this就代表哪个对象。


this的应用:当定义类中功能时,该函数内部要用到调用该函数的对象时,这时用this来表示这个对象。
  但凡本类功能内部使用了了本类对象,都用this表示。存在于栈内存中。


public class Example{
         String str=new String("good"); // 成员变量,作用于整个类Example
         char[] ch = {'a','b','c'};                       
         public void change(String str,char ch[])
        {            
          str="test ok"; //局部变量与成员变量相同时改为 this.str="test ok";因为this代表它所在函数所属对象的引用
          ch[0]='g';
        }

         public static void main(String args[])
        {
          Example ex=new Example();            
          ex.change(ex.str,ex.ch);         //调用change()方法      
          System.out.print(ex.str+" and ");
          Sytem.out.print(ex.ch);
      }
}

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马