//QuadString class //Hold 4 strings //Demonstrates Object methods: toString, equals, and clone //9/13/2006 public class QuadString { //instance variables: private String one; private String two; private String three; private String four; public QuadString(String one, String two){ //constructor: has default values for two and three this.one = one; this.two = two; this.three = "word3"; this.four = "word4"; } public String toString() { //returns a String representation of the Object String returnStr = "one is " + this.one + "\n"; returnStr += "two is " + this.two + "\n"; returnStr += "three is " + this.three + "\n"; returnStr += "four is " + this.four + "\n"; return returnStr; } public boolean equals(Object other){ //compares this object of QuadString to another //note we do not need else if since it returns at any point that it discovers they are not equal if (!(other instanceof QuadString)) return false; //cast the Object other in the QuadString ot //alternatively we could cast each use of other (not fun) QuadString ot = (QuadString)other; if (!(this.one.equals(ot.one))) return false; if (!(this.two.equals(ot.two))) return false; if (!(this.three.equals(ot.three))) return false; if (!(this.four.equals(ot.four))) return false; //all strings are equal so they must be the same return true; } public Object clone() { //create a new object which is the same as "this" QuadString other = new QuadString(this.one, this.two); return other; } public static void main (String [] args) { //main class method being used to test class/objects QuadString qs = new QuadString("hello world", "string"); //the following lines are logically equivalent: (toString is called in the first as well) System.out.println(qs); System.out.println(qs.toString()); //get a copy of qs (qs2 is it's own object) QuadString qs2 = (QuadString)qs.clone(); //note clone returns an Object, so we must cast it if (qs == qs2){ //this will not be printed because they are not the same exact instance/object of QuadString System.out.println("They are equal with == (not true)"); } if (qs.equals(qs2)){ //this is true because the equals method compares the content System.out.println("They're equal with equals method"); } } }