0

I'm used to working with languages that explicitly allow you to work with references/pointers, what I'm attempting to do relies upon that present.

If I have an object of class Foo and I have three objects of class Bar. How do I have all three objects of class Bar reference the one instance of Foo?

(I am relying on side effects)

If this is possible in Java at all (which I believe gives you a copy of a reference, but I've read conflicting information and now remain a little confused)

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Mattisdada
  • 979
  • 1
  • 15
  • 24
  • 3
    `bar1.field = foo; bar2.field = foo; bar3.field = foo;` – Sotirios Delimanolis Oct 22 '15 at 22:00
  • 1
    Pass `Foo foo` as argument to a method in `Bar` to receive a `Foo` variable. Then, you will have a copy of the reference stored in `Bar`, and any instance of `Bar` could alter the state of that `Foo` (if possible). If you're asking if any instance of `Bar` can replace the object reference in `Foo` for the other instances of `Bar`, it's not possible since Java is pass by value. – Luiggi Mendoza Oct 22 '15 at 22:00
  • 1
    If you can provide a little more detail on your use case, it might be evident on what you need. Is Foo a Singleton? Is Bar composed with a Foo instance? A little more help in what you are looking for can help give a better answer. – purring pigeon Oct 22 '15 at 22:03

1 Answers1

3

If this is possible in Java at all (which I believe gives you a copy of a reference, but I've read conflicting information and now remain a little confused)

Maybe you're used to using languages like C which treat memory as one giant array and which use pointers (and pointers to pointers) to data structures. Java differs from C by using references (instead of pointers) and objects (instead of structures).

The analog to pointers in Java is the reference variable which stores a reference to an object. The value of a reference variable is a pointer, but in Java you never use the pointer value itself, only the object to which it refers.

If you have a class defined this way:

public class Bar {
    private Foo fooRef;

   public Bar(Foo foo) {
       this.fooRef = foo;
   }

   :
   :
}

Note that Bar is defined to have a mutable instance field, fooRef which will hold a reference to an object of type Foo.

The following will instantiate three instances of Bar, each with a reference to the same Foo object:

Foo myFoo = new Foo();

Bar bar1 = new Bar(myFoo);
Bar bar2 = new Bar(myFoo);
Bar bar3 = new Bar(myFoo);

Because the instance field, fooRef is mutable, the object which contains it can be mutated by any method that has access to the field. This enables the side effects you're looking for (although mutable fields are a particular concern in concurrent programming).

scottb
  • 9,908
  • 3
  • 40
  • 56