Java Reference
In-Depth Information
The Pattern x = change(x)
Consider the following short program:
1 import java.awt.*;
2
3 public class PointTest {
4 public static void main(String[] args) {
5 Point p = new Point(2, 8);
6 System.out.println("p = " + p);
7 change(p);
8 System.out.println("now p = " + p);
9 }
10
11 public static void change(Point q) {
12 q.translate(3, 5);
13 q = new Point(-7, -14);
14 System.out.println("q = " + q);
15 }
16 }
The code in main constructs a Point object and passes it as a parameter. Inside
the method we translate the coordinates of the Point object. This change is reflected
in the original Point object because when we pass an object as a parameter, the
parameter gets a copy of the reference to the object.
But what about the final line of the method that constructs a new Point ? Does
that change the main method's variable p ? The answer is no. The overall output for
this version of the program is as follows:
p = java.awt.Point[x=2,y=8]
q = java.awt.Point[x=-7,y=-14]
now p = java.awt.Point[x=5,y=13]
One of the changes (translating the coordinates) has an effect, but the other (con-
structing a new Point ) does not. This happens because when we pass an object as a
parameter, the parameter gets a copy of the reference to the object. When we call the
change method, the variable q is set up as a copy of the variable p :
p
x
2
y
8
q
 
 
Search WWH ::




Custom Search