对象引用的怪异行为,“鬼”目的
我正在弄乱一些示例代码,以检查我是否了解对象在偶然发现这种情况时彼此指的行为:
public class exampleClass {
int testInt;
exampleClass pointedObj;
public static void main(String args[]) {
exampleClass Obj1= new exampleClass();
exampleClass Obj2= new exampleClass();
exampleClass Obj3= new exampleClass();
Obj1.pointedObj= Obj3;
Obj2.pointedObj= Obj3;
Obj1.testInt= 1;
Obj2.testInt= 2;
Obj3.testInt= 3;
Obj3= Obj2;
System.out.println(Obj1.pointedObj.testInt);
System.out.println(Obj2.pointedObj.testInt);
System.out.println(Obj3.pointedObj.testInt);
System.out.println(Obj1.testInt);
System.out.println(Obj2.testInt);
System.out.println(Obj3.testInt);
}
}
我希望在控制台上看到:
2
2
2
1
2
2
但是我得到了:
3
3
3
1
2
2
这让我发疯了。如果对象都没有上述值,为什么尖的对象仍然保持“ 3”值?我敢肯定,周围有一个类似的问题,但是我没有能力寻找特定的东西。
我已经感谢任何帮助。
I was messing around with some sample code to check if I understood how objects behave when referring to one another when I stumbled upon this situation:
public class exampleClass {
int testInt;
exampleClass pointedObj;
public static void main(String args[]) {
exampleClass Obj1= new exampleClass();
exampleClass Obj2= new exampleClass();
exampleClass Obj3= new exampleClass();
Obj1.pointedObj= Obj3;
Obj2.pointedObj= Obj3;
Obj1.testInt= 1;
Obj2.testInt= 2;
Obj3.testInt= 3;
Obj3= Obj2;
System.out.println(Obj1.pointedObj.testInt);
System.out.println(Obj2.pointedObj.testInt);
System.out.println(Obj3.pointedObj.testInt);
System.out.println(Obj1.testInt);
System.out.println(Obj2.testInt);
System.out.println(Obj3.testInt);
}
}
I expected to see on the console:
2
2
2
1
2
2
But instead I get:
3
3
3
1
2
2
And it's driving me crazy. Why does the pointed objects still hold the value "3" if none of the objects holds said value? I'm sure there is a similar question around, but I don't have the power to search for something this specific.
I'm already grateful for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
存储在任何对象变量中的实际“值”是对对象的引用,而不是对象本身。当您将一个这样的变量的值分配给另一个变量时,您将分配该引用。
让我们浏览代码。
首先,您创建三个对象。让我们调用实际对象A,B和C。您将这些对象的引用分配给变量。
然后,您进行一些作业。在这里,您要使用存储在
obj3
中的参考,并在某些实例成员中存储它。然后,您对另一个实例成员进行一些分配。
最后,您将
obj2
分配给obj3
。因此,obj3
现在指向对象B。但这不会将您先前分配给pointedObj
成员的内容更改。它们仍然包含对objectc的引用。The actual "value" stored in any object variable is a reference to an object, not the object itself. When you assign the value of one such variable to another, you are assigning that reference.
Let's walk through the code.
First you create three objects. Let's call the actual objects A, B, and C. You assign references to those objects to the variables.
Then you make some assignments. Here you are taking the reference stored in
Obj3
and storing it in some instance members.Then you make some assignments to another instance member.
Finally, you assign
Obj2
toObj3
. SoObj3
now points to object B. But this does not change what you previously assigned to thepointedObj
members. They still contain references to objectC.