Re: Immutability
On 4/8/2010 11:43 PM, Numeron wrote:
Hi,
Im trying to create getter/setter methods for an Object... Since one
of the global varibles in question is an Object itself (specifically a
Point that relates to a location), Im not sure how to correctly set up
the object to be immutable when retrieved through the getter method.
Currently I have:
public Point getLocation(){
final Point location = this.location;
return location;
}
This has exactly the same effect as
public Point getLocation() { return location; }
I am certain this wont work for my purpose because final does not
protect the x,y variables inside the location Point (Im not 100% sure
if it even protects the returned variable).
No, not even that. The `final' in your example means only
that the local reference variable `location' cannot be changed
after initialization. It says nothing at all about the Point
the variable refers to, nor about what the caller might do with
the value returned.
I could make 2 methods getX() and getY() to solve this problem
specifically but it may rise again in the future in the form of a more
complex Object that cannot be solved so easily. Is there any way that
I can create a refence to the location that is protected from change,
while other references (like the global variable in the main object
itself) are not?
No way I can think of. If the Point class allows mutation
(as java.awt.Point does), anybody with a reference to a Point
object can mutate it. As Patricia Shanahan suggests, you might
return a clone of your Point and allow the caller to muck with
it freely. Alternatively, you could implement a PermanentPoint
class of your own, one that has getters but no setters. If you
need to modify the PermanentPoint within your own code but make
it "immutable to outsiders," you could write setters that are
private or package-private, but not public. (A PermanentPoint,
though, can't be a java.awt.Point; this may or may not be a
problem for your purposes.)
--
Eric Sosman
esosman@ieee-dot-org.invalid