Java 覆盖此变量的正确方法是什么?
在方法中覆盖现有变量时,下面类型为Java 覆盖此变量的正确方法是什么?,java,parameters,variable-assignment,Java,Parameters,Variable Assignment,在方法中覆盖现有变量时,下面类型为Thing的someThing,正确的方法是什么 doSomething(someThing); void doSomething(Thing thing){ //... thing = new Thing(...); // receives warning in Eclipse } 或 您的第一个示例不会更改调用者中的变量someThing。分配仅在doSomething方法中可见 第二个示例确实更改了调用者中的内容 因此,如果您想更改调用
Thing
的someThing
,正确的方法是什么
doSomething(someThing);
void doSomething(Thing thing){
//...
thing = new Thing(...); // receives warning in Eclipse
}
或
您的第一个示例不会更改调用者中的变量
someThing
。分配仅在doSomething
方法中可见
第二个示例确实更改了调用者中的内容
因此,如果您想更改调用者中的内容,那么选项2是可行的,而选项1不是
看看为什么会这样
假设以下代码,以及一个具有print方法和字符串成员的Thing
void foo() {
Thing one = new Thing("hello"); // 1
bar(one);
one.print(); // 5
}
void bar(Thing two) { // 2
two = new Thing("bye"); // 3
} // 4
点1
处的赋值首先创建一个新对象:
Thing{data="hello"}
然后将引用存储在one
中:
one *----- refs --------v
Thing{data="hello"}
在点2
处输入bar
时,将创建对同一对象的新引用:
one *----- refs --------v
Thing{data="hello"}
two *----- refs --------^
然后行3
执行与行1
相同的操作,即创建一个新的对象:
one *----- refs --------v
Thing{data="hello"}
two *----- refs --------^
Thing{data="bye"}
然后在two
中存储对该新对象的引用:
one *----- refs --------v
Thing{data="hello"}
two *----- refs --------v
Thing{data="bye"}
请注意,只修改了two
。分配更改了two
所指的内容
当您从bar
返回时,第4行的two
超出范围,“bye”对象不再有任何引用它的内容(最终将被垃圾收集)
因此,在点5
,正如您所看到的,hello
将被打印-任何东西都不会改变one
所指的对象。ooh。。。我可能搞砸了这是为什么?是不是因为我在第一种情况下覆盖了对某物的引用?
one *----- refs --------v
Thing{data="hello"}
two *----- refs --------v
Thing{data="bye"}
one *----- refs --------v
Thing{data="hello"}
Thing{data="bye"} // dead, will be collected