Shifting the Bits of My Mind

June 2009

06/17/2009

The Java programming language is reference based, which given the original goal to have a completely object oriented language makes sense because objects are heap explicit. However this has some unforeseen side effects. It is common to see code like this:

public class Foo{ private FooBar fooBar;

public FooBar getFooBar(){ return fooBar; }}

Where this causes unforeseen issues is that line return fooBar; since java is a reference based language, rather than return a copy of the object fooBar like you might expect it returns the actual object fooBar! This is easily verifiable with debugger. So what does this mean... It means that the code above is (almost) semantically equivalent to this:

public class Foo{ public FooBar fooBar;

}

Now I did say almost semantically equivalent... because they're not exactly the same. In the first you can modify the private object but you cannot assign to it, in the second one you can because the code access permission is public.

This clearly is not what most people think of when they create a getter method, however it is critical that they do! In a reference based language all objects are on the heap, thus to access them you must resolve a pointer, java hides this, however it is still there and is very apparent in this situation. To pass a clone of the object the programmer must either call the clone() method or use a copy constructor.

However there are advantages both ways, a programmer can use referenced based passing to expose functionallity that would otherwise be denied for encasulation reasons, or they can save memory and time by recycling the reference.