How to pass an object between multiple classes? Java

13,544

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.

Share:
13,544
Takkun
Author by

Takkun

Updated on June 04, 2022

Comments

  • Takkun
    Takkun almost 2 years
    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?