gpt4 book ai didi

java - 传递对象Java

转载 作者:行者123 更新时间:2023-12-01 19:01:31 25 4
gpt4 key购买 nike

以下 Java 代码有什么区别?我无法清楚地理解 Java 中对象是如何传递的。谁能解释一下下面的代码。

package cc;

public class C {

public static class Value {
private String value;

public void setValue(String str) {
value=str;
}

public String getValue() {
return value;
}
}



public static void test(Value str) {
str.setValue("test");
}

public static void test2(Value str) {
str=new Value();
str.setValue("test2");
}
public static void main(String[] args) {
String m="main";
Value v=new Value();
v.setValue(m);
System.out.println(v.getValue()); // prints main fine
test(v);
System.out.println(v.getValue()); // prints 'test' fine
test2(v);
System.out.println(v.getValue()); // prints 'test' again after assigning to test2 in function why?
}
}

最佳答案

test2() 中,创建了一个新实例,并且您在较新的实例中设置值,而不是在传递引用的对象中设置值

public static void test2(Value str) {
str=new Value();
str.setValue("test2");
}

另请参阅

关于java - 传递对象Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12086270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com