Passing and Returning Object References
What happens when objects are passed to and returned from methods: parameters receive copies of references, so methods can change mutable objects; reassigning a parameter changes nothing outside; returned references can expose private state; and private access works class by class.
When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method can use the reference to alter the object's state, so it is good practice not to modify mutable parameters unless the specification requires it. When a return expression evaluates to an object reference, the reference itself is returned, not a copy. And methods cannot access the private data and methods of a parameter unless the parameter is the same type as the method's enclosing class.
1Reference Parameters
Java passes every argument by value, but for objects the value being copied is a reference. When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. After the call begins, the caller's variable and the method's parameter are two arrows pointing at one object.
This is efficient, since an object of any size is passed by copying one reference, and it has a direct consequence: anything the method does to the object through its parameter is visible to the caller. Anything the method does to the parameter variable itself, such as reassigning it, is not.
| Inside the method | Effect on the caller's object | Effect on the caller's variable |
|---|---|---|
Call a mutator through the parameter (p.moveBy(1, 1)) | Changed | Still refers to the same object |
Reassign the parameter (p = new Point(0, 0)) | Unchanged | Unchanged |
Call only accessors (p.getX()) | Unchanged | Unchanged |
2Changing a Mutable Argument
A mutable object is one whose state can change after it is created, such as a Point with a moveBy method. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object. A method that calls p.moveBy(1, 1) moves the caller's point.
Sometimes that is exactly the intent, for example a method whose documented job is to adjust an object. But it is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification. Unexpected changes to a caller's object are a classic source of bugs, because nothing at the call site suggests the object might change.
A Method That Moves the Caller's Point
Predict the output.
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveBy(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
public String show()
{
return "(" + x + ", " + y + ")";
}
public int manhattanTo(Point other)
{
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
}
public class Tools
{
public static void nudge(Point p)
{
p.moveBy(1, 1);
}
}
(4, 5)
- 1The call copies the reference.
pandspotrefer to the samePoint(Figure 1). - 2
p.moveBy(1, 1)changes that one object. - 3The caller sees the change, because
spotstill refers to the same object.
Reading a Parameter Without Changing It
This method needs only to read its parameter, so it does not modify it. Predict the output.
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveBy(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
public String show()
{
return "(" + x + ", " + y + ")";
}
public int manhattanTo(Point other)
{
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
}
public class Tools
{
public static String quadrantLabel(Point p)
{
if (p.getX() >= 0 && p.getY() >= 0)
{
return "first quadrant";
}
return "elsewhere";
}
}
first quadrant
(6, 8)
- 1Accessors only. The method calls
getXandgetY, never a method that changes the point. - 2The caller's object is unchanged: (6, 8).
A method that receives a reference to a mutable object can change that object. Check the method's documentation, or its code, before assuming your object will be the same after the call.
3Reassigning a Parameter
Assigning a new reference to a parameter, as in p = new Point(0, 0);, changes only the method's own copy of the reference. The parameter now refers to a different object, but the caller's variable still refers to the original object, which was not modified at all.
The distinction between using the arrow (calling a method through it) and redirecting the arrow (assigning to the parameter) explains every case. Strings fall into the second group automatically: since a String cannot be changed, every "change" to a string parameter is really a reassignment, and the caller's string is never affected.
Pointing the Parameter Somewhere Else
Predict the output.
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveBy(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
public String show()
{
return "(" + x + ", " + y + ")";
}
public int manhattanTo(Point other)
{
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
}
public class Tools
{
public static void reset(Point p)
{
p = new Point(0, 0);
}
}
(3, 4)
- 1
p = new Point(0, 0)makes the parameter refer to a new object. - 2The caller's variable is untouched:
spotstill refers to the original (3, 4), which was never modified (Figure 2).
A String Parameter Cannot Be Changed
Predict the output.
public static void excite(String s)
{
s = s + "!";
System.out.println("inside: " + s);
}
inside: hello!
outside: hello
- 1
s + "!"builds a newString, and the assignment pointssat it. - 2The original string cannot be changed, and
wordstill refers to it.
String to a method can never change the caller's text.A method cannot make the caller's variable refer to a different object by assigning to its parameter. If a method needs to provide a new object, it should return the new object, and the caller should assign the result.
4Returning References
When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object. An accessor that returns a reference to a private mutable instance variable therefore gives the caller an alias of the object's internal state; the caller can then change the object without calling any of its mutators.
To keep private state private, an accessor can return a copy of a mutable object instead, built with the same data. Returning primitives and strings never has this problem: primitives are returned as copies of their values, and strings cannot be changed.
| Accessor returns | Caller receives | Can the caller change the object's state? |
|---|---|---|
A primitive (int, double, boolean) | A copy of the value | No |
A String | A reference to an immutable object | No |
| A reference to a private mutable object | An alias of the private object | Yes: state is exposed |
| A new copy of that object | A separate object | No |
An Accessor That Leaks Private State
Compare two versions of getLocation.
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveBy(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
public String show()
{
return "(" + x + ", " + y + ")";
}
public int manhattanTo(Point other)
{
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
}
public class Marker
{
private Point location;
public Marker(int x, int y)
{
location = new Point(x, y);
}
public Point getLocation()
{
return location;
}
}
(7, 7)
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveBy(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
public String show()
{
return "(" + x + ", " + y + ")";
}
public int manhattanTo(Point other)
{
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
}
public class Marker
{
private Point location;
public Marker(int x, int y)
{
location = new Point(x, y);
}
public Point getLocation()
{
return new Point(location.getX(), location.getY());
}
}
(2, 2)
- 1First version.
return location;returns the reference to the marker's own privatePoint. The caller'slocbecomes an alias, andloc.moveBymoves the marker: (7, 7). - 2Second version. The accessor returns a new
Pointwith the same coordinates. Moving the copy leaves the marker at (2, 2).
return location; hands out a reference to the object's internal Point. Code that changes the returned point changes the marker, bypassing encapsulation. Return a copy when callers should only read the value.
5Private Access and Parameters
Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method's enclosing class. Inside the Point class, a method with a parameter Point other may read other.x directly, because privacy in Java is per class, not per object.
For parameters of any other class, a method must use that class's public methods, exactly as any outside code would. This rule lets objects of the same class cooperate efficiently, as when comparing coordinates or copying data, while still keeping each class's internals hidden from all other classes.
| Code location | Expression | Allowed? |
|---|---|---|
Method inside Point, parameter Point other | other.x | Yes |
Method inside Point, parameter Marker m | A private field of m | No |
Any method in Main | p.x | No |
| Anywhere | p.getX() | Yes (public) |
Reading Another Point's Private Coordinates
manhattanTo reads other.x and other.y directly. Predict the output, then explain why the second program does not compile.
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveBy(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
public String show()
{
return "(" + x + ", " + y + ")";
}
public int manhattanTo(Point other)
{
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
}
7
public class Point
{
private int x;
private int y;
public Point(int x0, int y0)
{
x = x0;
y = y0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void moveBy(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
public String show()
{
return "(" + x + ", " + y + ")";
}
public int manhattanTo(Point other)
{
return Math.abs(x - other.x) + Math.abs(y - other.y);
}
}
- 1Distance. |1 − 4| + |2 − 6| = 3 + 4 = 7.
- 2Why
other.xis allowed.manhattanTois written insidePoint, andotheris also aPoint; private access is granted to the whole class. - 3Why
a.xfails inMain.Mainis a different class, soxis off limits there.
Inside Marker, a Point parameter's x is off limits even though the code is inside a class; it is the wrong class. Use p.getX().
6Good Practice With References
Three habits prevent most reference surprises. Do not modify mutable parameters unless the method's documented purpose is to do so. When storing a mutable object received from outside, or returning one held inside, use a copy if the two sides should stay independent. And when reading code, ask of each method call whether it might change an object that other variables also refer to.
These habits are the practical side of encapsulation. An object stays in control of its own state only if no outside code holds a reference to its mutable internals, and callers can trust their own objects only if the methods they call change those objects deliberately and visibly.
Four Habits for References in Methods
1. Same Object, Two Arrows
A reference parameter shares the caller's object.
2. Use the Arrow, Not Redirect It
Mutating shows outside; reassigning does not.
3. Copy Mutable Internals Out
Returned references are aliases.
4. Private Is Per Class
Same-class parameters may use private members.
When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object, and it is good programming practice to not modify mutable objects passed as parameters unless required in the specification. When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object. Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method's enclosing class.