如何在多个类之间传递对象? Java的 [英] How to pass an object between multiple classes? Java

查看:113
本文介绍了如何在多个类之间传递对象? Java的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

如何创建一个循环,其中一个类的更改反映在另一个类中?

How can I make a cycle where one change to a class is reflected in the other class?

推荐答案

这已经是对象在Java中的运作方式。您的代码已经完成了您想要的操作。

That's already exactly how objects work in Java. Your code already does what you want it to.

当您将 theBar 传递给时FooClass 构造函数,它将 theBar 的值传递给 BarClass,它是引用 对象。 ( theBar 本身是按值传递的 - 如果你在<$ c $中写了 foo = new FooClass(); c> BarClass 构造函数,它不会改变引用的对象 theBar .Java是严格按值传递的,它只是值通常是引用。)

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.)

使用 theBar.foo.a 更改该对象中的值时,请查看在 a 的值再次使用 theFoo.a 将看到更新的值。

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.

基本上,Java不会复制对象,除非你真的要求它。

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

这篇关于如何在多个类之间传递对象? Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆