Take the 2-minute tour ×
public class FooClass {
    BarClass bar = null;
    int a = 0;
    int b = 1;
    int c = 2;

    public FooClass(BarClass bar) {
        this.bar = bar;

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

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?

share|improve this question
Did you try it? It is exactly the way you want it. –  Howard Sep 24 '11 at 6:55
add comment

1 Answer

up vote 4 down vote accepted

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|improve this answer
add comment

Your Answer


