如何在多个类之间传递对象?爪哇

发布于 2024-12-06 19:17:27 字数 763 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光瘦了 2024-12-13 19:17:27

这正是 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 the FooClass constructor, that's passing the value of theBar, which is a reference to 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.)

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.

Basically, Java doesn't copy objects unless you really ask it to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文