java 如何在多个类之间传递对象?爪哇
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7537526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass an object between multiple classes? Java
提问by Takkun
public class FooClass {
BarClass bar = null;
int a = 0;
int b = 1;
int c = 2;
public FooClass(BarClass bar) {
this.bar = bar;
bar.setFoo(this);
}
}
public class BarClass {
FooClass foo = null;
public BarClass(){}
public void setFoo(FooClass foo) {
this.foo = foo;
}
}
elsewhere...
别处...
BarClass theBar = new BarClass();
FooClass theFoo = new FooClass(theBar);
theFoo.a //should be 0
theBar.foo.a = 234; //I change the variable through theBar. Imagine all the variables are private and there are getters/setters.
theFoo.a //should be 234 <-----
How can I pass an object to another class, make a change, and have that change appear in the original instance of the first object?
如何将对象传递给另一个类,进行更改,并使该更改出现在第一个对象的原始实例中?
or
或者
How can I make a cycle where one change to a class is reflected in the other class?
我怎样才能使一个班级的更改反映在另一个班级中的循环?
回答by Jon Skeet
That's already exactly how objects work in Java. Your code already does what you want it to.
这就是对象在 Java 中的工作方式。您的代码已经按照您的意愿行事。
When you pass theBar
to the FooClass
constructor, that's passing the value of theBar
, which is a referenceto a BarClass
object. (theBar
itself is passed by value - if you wrote foo = new FooClass();
in the BarClass
constructor, that wouldn't change which object theBar
referred to. Java is strictly pass-by-value, it's just that the values are often references.)
当您传递theBar
给FooClass
构造函数时,就是传递 的值theBar
,它是对对象的引用BarClass
。(theBar
本身是按值传递的 - 如果您foo = new FooClass();
在BarClass
构造函数中编写,则不会更改theBar
引用的对象。Java 是严格按值传递的,只是值通常是引用。)
When you change the value within that object using theBar.foo.a
, then looking at the value of a
again using theFoo.a
will see the updated value.
当您使用 更改该对象theBar.foo.a
中的值时,a
再次theFoo.a
查看using的值将看到更新后的值。
Basically, Java doesn't copyobjects unless you really ask it to.
基本上,Java 不会复制对象,除非您真的要求它。