如何在多个类之间传递对象?爪哇
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;
}
}
其他地方...
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 <-----
我如何将一个对象传递给另一个类,进行更改,并使该更改出现在第一个对象的原始实例中?
或者
我怎样才能建立一个循环,使一个类的更改反映在另一个类中?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这正是 Java 中对象的工作方式。您的代码已经执行了您想要的操作。
当您将
theBar
传递给FooClass
构造函数时,即传递了theBar
的值,它是对BarClass
对象。 (theBar
本身是按值传递的 - 如果您在BarClass
构造函数中编写foo = new FooClass();
,则不会改变theBar
引用的对象是严格按值传递的,只是这些值通常是引用。)当您使用
theBar.foo.a,然后查看值再次使用
theFoo.a
将会看到更新后的值。基本上,Java 不会复制对象,除非您确实要求这样做。
That's already exactly how objects work in Java. Your code already does what you want it to.
When you pass
theBar
to theFooClass
constructor, that's passing the value oftheBar
, which is a reference to aBarClass
object. (theBar
itself is passed by value - if you wrotefoo = new FooClass();
in theBarClass
constructor, that wouldn't change which objecttheBar
referred to. Java is strictly pass-by-value, it's just that the values are often references.)When you change the value within that object using
theBar.foo.a
, then looking at the value ofa
again usingtheFoo.a
will see the updated value.Basically, Java doesn't copy objects unless you really ask it to.