// It's always useful to define these methods // toString should return a String that represents the object public String toString() { String out = givenName + " " + familyName + " is " + age + " years old."; if (parent != null) { out += "\nParent: " + parent.toString(); } return out; }
public static void main(String args[]) { // Let's create a few objects BadMutablePerson p1 = new BadMutablePerson("", "Mr. Incredible", 37, null); BadMutablePerson p2 = new BadMutablePerson("", "Elastigirl", 35); BadMutablePerson p3 = new BadMutablePerson("Parr", "Dash", 13, p1); BadMutablePerson p4 = new BadMutablePerson("Parr", "Violet", 17, p1); BadMutablePerson p5 = p1; // We can use toString to print a representation of the object System.out.println("\nTESTING TOSTRING METHOD"); System.out.println(p1.toString()); // Java is smart enough that you don't actually need to call the method System.out.println(p2); System.out.println(p3); // Now let's try the equals method; this should print false System.out.println("\nTESTING EQUALS METHOD"); System.out.println( "Testing p1 with p4, expecting false as they are " + " different objects: " + p1.equals(p4)); System.out.println( "Testing p4 with p1, expecting false as they are " + " different objects: " + p4.equals(p1)); System.out.println( "Testing p1 with p2, expecting false as they are " + " different objects: " + p1.equals(p2)); // This is true System.out.println( "Testing p1 with p1, expecting true as they are " + " the same objects: " + p1.equals(p1)); System.out.println( "Testing p1 with p5, expecting true as they " + "point to the same object: " + p1.equals(p5)); System.out.println( "Testing parent of p3 with parent of p4, " + "expecting true, same parent: " + p3.getParent().equals(p4.getParent())); // We can now modify our objects because of the set methods System.out.println("\nTESTING SETTERS"); // Here is the starting object System.out.println(p1); // Now we modify it and check again p1.setAge(20); System.out.println(p1); p1.setFamilyName("Parr"); System.out.println(p5); // Let's make sure we've prevented privacy leaks System.out.println("\nTESTING PRIVACY LEAKS"); System.out.println(p3); System.out.println(p4); p1.setFamilyName(""); System.out.println(p3); System.out.println(p4); System.out.println("\nUh oh..."); }