初學Java的問題後並沒有改變,但我不明白怎麼稱呼按值(或參考)在下面的例子中工作 -爪哇 - 對象狀態的方法調用
怎麼來的字符串值沒有修改在我的自定義字符串對象處於退出方法後。 ?同樣的,其他類,如日期..
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";
}
啊..我明白了。感謝....本來,我的'你好(CustomStringObject O)'被實例化一個新的實例,如'O =新CustomStringObject()'我注意到hello方法之外,在instanation從未有過任何影響。這就是觸發問題的原因。 – 2012-08-03 19:04:40
@Jon很好的解釋。 Foo示例有所幫助。 +1 – 2014-03-06 04:52:09
如果調用者傳遞空引用,那麼我觀察到被調用者修改並不反映給調用者。爲什麼它是這樣呢? – 2015-09-29 10:40:06