日期:2014-05-20  浏览次数:20690 次

帮我看看对象的引用这两段代码
package string;

public class yinyongto {
     public static void main(String[] args) {
String str="hello";
fun(str);
System.out.println(str);
}
     public static void fun(String temp)
     {
      temp="world";
     }
}

结果是hello


下一段是
package string;
class demo
{
   int x=10;
}
public class index {
public static void main(String[] args) {
demo d= new demo();
d.x=30;
fun(d);
System.out.println(d.x);
}
public static void fun(demo temp)
{
temp.x=100;
}

}
结果是30  我想说为什么上一个的结果不是world temp不能修改了内容断开连接么


------解决方案--------------------
分清对象和对象引用的概念
1.对引用的操作
调用方法fun(str);时
str是实参,temp是形参,二者引用的是同一个String对象
对temp赋值,只是让它指向了其他对象,这不会影响str。
2.对所引用的对象的操作
调用方法fun(d);时
d是实参,temp是形参,二者引用的是同一个demo对象
所以temp.x就是d.x,改变temp.x就是改变了d.x