Search code examples
javareferenceside-effects

Working with references in Java to create side effects


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)


Solution

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