Because all object identifiers are references in Java, and because every object is created on the heap and garbage collected only when it is no longer used, the flavor of object manipulation changes, especially when passing and returning objects. For example, in C or C++, if you wanted to initialize some piece of storage in a method, youd probably request that the user pass the address of that piece of storage into the method. Otherwise, youd have to worry about who was responsible for destroying that storage. Thus, the interface and understanding of such methods is more complicated. But in Java, you never have to worry about responsibility or whether an object will still exist when it is needed, since that is always taken care of for you. You can create an object at the point that it is needed (and no sooner) and never worry about the mechanics of passing around responsibility for that object; you simply pass the reference. Sometimes the simplification that this provides is unnoticed. Other times it is staggering.
The downside to all this underlying magic is twofold:
- You always take the efficiency hit for the extra memory management (although
this can be quite small), and theres always a slight amount of
uncertainty about the time something can take to run (since the garbage
collector can be forced into action whenever you get low on memory). For most
applications, the benefits outweigh the drawbacks, and the hotspot technologies
in particular have sped things up to the point where its not much of an
- Aliasing: Sometimes you can accidentally end up with two references to the
same object, which is a problem only if both references are assumed to point to
a distinct object. This is where you need to pay a little closer
attention and, when necessary, clone( ) or otherwise duplicate an
object to prevent the other reference from being surprised by an unexpected
change. Alternatively, you can support aliasing for efficiency by creating
immutable objects whose operations can return a new object of the same type or
some different type, but never change the original object so that anyone aliased
to that object sees no change.
href="TIJ319_022.htm"> and never call the Object.clone( ) method, thus eliminating the need to implement Cloneable and catch the CloneNotSupportedException. This is certainly a reasonable approach, and since clone( ) is supported so rarely within the standard Java library, it is apparently a safe one as well.