Java - 对象状态在方法调用后不会更改
2022-09-03 18:18:22
初学者Java问题,但我无法理解按值调用(或参考)在下面的示例中是如何工作的 -
为什么在我的自定义字符串对象退出方法后,String 值没有被修改。?与日期等其他类相同。
public class StringMadness {
public static void main(String[] args) {
String s = "Native String";
CustomStringObject cs = new CustomStringObject();
System.out.println("Custom String Before: " + cs.str);
hello(cs);
System.out.println("Custom String After: " + cs.str);
System.out.println("Native String Before: " + s);
hello(s);
System.out.println("Native String After: " + s);
}
private static void hello(String t) {
t = "hello " + t;
}
private static void hello(CustomStringObject o) {
o.str = "hello " + o.str;
}
}
class CustomStringObject {
String str = "Custom String";
}