jam
jam

Reputation: 1293

How to bind references of two objects?

If I have 2 Objects

Foo foo;
Foo bar = foo;

they both point initially to null.

If foo get's initialized

foo = new Foo();

bar references to null, but I want it to be bind to foo.

So every change of the foo reference effects the bar reference to be the same.

Is there a way to automatically let bar point to the same address as foo,

even if it changes or do I have to call it manually ?

foo = new Foo();
bar = foo;

Upvotes: 0

Views: 97

Answers (3)

f1sh
f1sh

Reputation: 11942

You can use a workaround by creating something like a pointer class.

class Pointer <T> {
  T target = null;
  Pointer(T target){
    this.target = target;
  }
  static Pointer nullPointer(){
    return new Pointer(null);
  }
  public void setTarget(T target){
    this.target = target;
  }
  public T getTarget(){
    return target;
  }
}

You can use it like this:

Pointer<Foo> foo = Pointer.nullPointer(); //target=null
Pointer<Foo> bar = foo;           //bar now also "points" to null
foo.setTarget(new Foo()); //now BOTH have the new object as the target

Upvotes: 1

Homo Filmens
Homo Filmens

Reputation: 116

Java is Pass-by-value, not pass-by-reference. The reference of bar should not be the same of foo

Upvotes: 0

vogomatix
vogomatix

Reputation: 5061

Both foo and bar are not really objects, but references to objects.

In your initial declaration, you are setting both to undefined, or more accurately foo is undefined, and you are setting bar to the same value. However, even if you had initialised foo, the answer would be the same.

When you set the value of foo to a new object (new Foo), you are still leaving bar undefined.

So the answer is, yes, you have to do it manually.

Upvotes: 1

Related Questions