public class TestRefObj {
public static void main(String[] args) {
Person person = new Person("xxxx");
TestRefObj testRefObj = new TestRefObj();
testRefObj.test(person);
System.out.println(person.x);
} public void test(Person p){
p = new Person("yyyy");
System.out.println(p.x);
}
}class Person{
public String x;
public Person(String x){
this.x = x;
}
}运行结果是
yyyy
xxxx函数调用不是应该引用传递吗?
我觉得应该是
yyyy
yyyy
请高手解释下
public static void main(String[] args) {
Person person = new Person("xxxx");
TestRefObj testRefObj = new TestRefObj();
testRefObj.test(person);
System.out.println(person.x);
} public void test(Person p){
p = new Person("yyyy");
System.out.println(p.x);
}
}class Person{
public String x;
public Person(String x){
this.x = x;
}
}运行结果是
yyyy
xxxx函数调用不是应该引用传递吗?
我觉得应该是
yyyy
yyyy
请高手解释下
p = new Person("yyyy");// 传递的p值已经改变,引用了另一个对象
System.out.println(p.x);
}
对于引用类型的实参,同样是拷贝一份给形参,但是拷贝的是引用,也就是指向同一个对象的地址,传递给方法的是指向同一个对象的引用,里面的操作是对同一个对象的操作,反过来你在用实参调用对象,对象也许改变了
person指向A对象(xxxx)test(person)public void test(Person p){ //1
p = new Person("yyyy");//2
System.out.println(p.x);
}
} 1处 person的引用赋给p,即这时person和p指向同一个对象A(xxxx)
2处 新创建了一个对象B(yyyy),并且p指向了这个B对象(yyyy),这时p.x就是B对象的x值了
引用传参说的是对于同一个对象而已。
在mian中 说先是用
Person p=new Person();
然后又在
public void test(String a){
Person p=new Person()
}
也就是说Person 类你创建了两次,都不是一个对象怎么引用。