import java.awt.Point; /**** * * This is a simple tester for the ShallowCircle and DeepCircle classes. It * shows how undesirable things can happen to shallow objects, while these * things cannot happen to the deep versions. * */ public class CircleTester { public static void main(String[] args) { // Construct one point to send to the circle constructors. Point p = new Point(10,20); /* * Construct two shallow circles and two deep ones, sending all of the * constructors the same point object. */ ShallowCircle sc1 = new ShallowCircle(p, 5.0); ShallowCircle sc2 = new ShallowCircle(p, 5.0); DeepCircle dc1 = new DeepCircle(p, 5.0); DeepCircle dc2 = new DeepCircle(p, 5.0); /* * Mutate the center of sc1, which has the undesired effect of also * mutating the center of sc2. This is due to the shallow return of a * reference from getCenter, rather than a deep copy of the Point. */ sc1.getCenter().x = 100; System.out.println("\nexpect 10, actual result = " + sc2.getCenter().x + " (problem due to shallow getCenter)\n"); /* * Now notice that neither of centers of the deep circles were mutated. */ System.out.println("expect 10, actual result = " +dc2.getCenter().x + " (as expected, due to deep getCenter)"); System.out.println("expect 10, actual result = " +dc2.getCenter().x); /* * Mutate the point from outside of the Circle class, which has the * undesirable effect of mutating both shallow circles. This is due to the * shallow assignment of a reference in the constructor, rather than making * a (deep) copy of the Point parameter. */ p.y = 200; System.out.println("\nexpect 20, actual result = " +sc1.getCenter().y + " (problem due to shallow constructor)"); System.out.println("expect 20, actual result = " +sc2.getCenter().y); /* * Now notice that neither of the deep circles was mutated by the external * mutation of the Point p. */ System.out.println("\nexpect 20, actual result = " +dc1.getCenter().y + " (as expected, due to deep Constructor)"); System.out.println("expect 20, actual result = " +dc2.getCenter().y); /* * Create all four circles again, this time given each of them a new center * point, rather than a shared center point. */ ShallowCircle sc3 = new ShallowCircle(new Point(10,20), 5.0); ShallowCircle sc4 = new ShallowCircle(new Point(10,20), 5.0); DeepCircle dc3 = new DeepCircle(new Point(10,20), 5.0); DeepCircle dc4 = new DeepCircle(new Point(10,20), 5.0); /* * Notice how sc3.equals(sc4) is false even though they have the same * center and diameter values. This is due to shallow implementation * equality. */ System.out.println("\nexpect true, actual result = " +sc3.equals(sc4) + " (problem due to shallow equals)"); /* * Now notice that dc3.equals(dc4) is true, due to the deep implementation * of equality. */ System.out.println("\nexpect true, actual result = " +dc3.equals(dc4) + " (as expected, due to deep equals)"); } }