我创建了以下测试来了解 Java 如何处理对象,这让我很困惑。
public class MyClass
{
public String text = "original";
public MyClass(String text)
{
this.text = text;
}
}
然后我创建了以下 2 个场景:
1.
String object1 = new String("original");
String object2 = new String("original");
object2 = object1;
object2 = "changed";
System.out.println(object1);
System.out.println(object2);
结果:
original
changed
2.
MyClass object1 = new MyClass("object1");
MyClass object2 = new MyClass("object2");
object2 = object1;
object2.text = "changed";
System.out.println(object1.text);
System.out.println(object2.text);
结果:
changed
changed
现在为什么文本字段像静态字段一样共享?