Java Reference
In-Depth Information
object references can usually be changed—often referred to as mutation of object
Java tries to simplify a concept that often confused C++ programmers—the differ‐
ence between “contents of an object” and “reference to an object.” Unfortunately, it's
not possible to completely hide the difference, and so it is necessary for the pro‐
grammer to understand how reference values work in the platform.
Is Java “Pass by Reference”?
Java handles objects “by reference,” but we must not confuse this with the phrase
“pass by reference.” “Pass by reference” is a term used to describe the method-calling
conventions of some programming languages. In a pass-by-reference language, val‐
ues—even primitive values—are not passed directly to methods. Instead, methods
are always passed references to values. Thus, if the method modifies its parameters,
those modifications are visible when the method returns, even for primitive types.
Java does not do this; it is a “pass-by-value” language. However, when a reference
type is involved, the value that is passed is a copy of the reference (as a value). But
this is not the same as pass by reference. If Java were a pass-by-reference language,
when a reference type is passed to a method, it would be passed as a reference to the
The fact that Java is pass by value can be demonstrated very simply. The following
code shows that even after the call to manipulate() , the value contained in variable
c is unaltered—it is still holding a reference to a Circle object of radius 2. If Java
was a pass-by-reference language, it would instead be holding a reference to a radius
3 Circle :
public void manipulate ( Circle circle ) {
circle = new Circle ( 3 );
Circle c = new Circle ( 2 );
manipulate ( c );
System . out . println ( "Radius: " + c . getRadius ());
If we're scrupulously careful about the distinction, and about referring to object ref‐
erences as one of Java's possible kinds of values, then some otherwise surprising fea‐
tures of Java become obvious. Be careful—some older texts are ambiguous on this
point. We will meet this concept of Java's values again when we discuss memory and
garbage collection in Chapter 6 .
Important Methods of java.lang.Object
As we've noted, all classes extend, directly or indirectly, java.lang.Object . This
class defines a number of useful methods that were designed to be overridden by
classes you write. Example 5-1 shows a class that overrides these methods. The
Search WWH ::

Custom Search