我了解到,当您在Java中修改变量时,它不会更改它所基于的变量
int a = new Integer(5);
int b = a;
b = b + b;
System.out.println(a); // 5 as expected
System.out.println(b); // 10 as expected
Run Code Online (Sandbox Code Playgroud)
我假设对象有类似的东西.考虑这个课程.
public class SomeObject {
public String text;
public SomeObject(String text) {
this.setText(text);
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
Run Code Online (Sandbox Code Playgroud)
在我尝试这段代码后,我感到困惑.
SomeObject s1 = new SomeObject("first");
SomeObject s2 = s1;
s2.setText("second");
System.out.println(s1.getText()); // second as UNexpected
System.out.println(s2.getText()); // second as expected
Run Code Online (Sandbox Code Playgroud)
请向我解释为什么更改任何对象会影响另一个对象.我知道变量文本的值存储在两个对象的内存中的相同位置.
为什么变量的值是独立的但与对象相关?
另外,如果简单的赋值不能完成工作,如何复制SomeObject?
public class DrumKitTestDrive {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Echo e1 = new Echo();
Echo e2 = new Echo();
// **e2 = e1;**
int x=0;
while( x < 4 ){
e1.hello();
e1.count = e1.count + 1;
if(x==3){
e2.count = e2.count + 1;
}
if(x>0){
e2.count = e2.count + e1.count;
}
x = x + 1;
}
System.out.print(e2.count);
}
}
class Echo {
int count = 0;
void hello(){
System.out.println("Hellooooo...."); …Run Code Online (Sandbox Code Playgroud)