/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
import java.awt.Point;
public class ModificationTest extends ReferenceTest {
public static void main(String[] args) {
Point p1 = new Point(1, 2); // Assign Point to p1
Point p2 = p1; // p2 is new reference to *same* Point
print("p1", p1); // (1, 2)
print("p2", p2); // (1, 2)
munge(p2); // Changes fields of the *single* Point
print("p1", p1); // (5, 10)
print("p2", p2); // (5, 10)
}
public static void munge(Point p) {
p.x = 5;
p.y = 10;
}
}
/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
import java.awt.Point;
public class ReferenceTest {
public static void main(String[] args) {
Point p1 = new Point(1, 2); // Assign Point to p1
Point p2 = p1; // p2 is new reference to *same* Point
print("p1", p1); // (1, 2)
print("p2", p2); // (1, 2)
triple(p2); // Doesn?t change p2
print("p2", p2); // (1, 2)
p2 = triple(p2); // Have p2 point to *new* Point
print("p2", p2); // (3, 6)
print("p1", p1); // p1 unchanged: (1, 2)
}
public static Point triple(Point p) {
p = new Point(p.x * 3, p.y * 3); // Redirect p
return(p);
}
public static void print(String name, Point p) {
System.out.println("Point " + name + "= (" +
p.x + ", " + p.y + ").");
}
}
Aug 29
