RU beehive logo ITEC dept promo banner
ITEC 120
2010fall
ibarland

homeinfolectslabsexamshws
tutor/PIsObject120 + its docsjava.lang docsjava.util docs

lect08b
equals, toString;

Notes:

Review hw05-soln-Student.java.

Equality:

Review: When comparing two object references, == returns true if (and only if) they reference (point to) the identically-same object.
What `equals` means: If you don't do anything to say otherwise, your own classes have a equals (inherited from java.lang.Object) which just does the same thing == does (?!):
  // Inside class java.lang.Object, deep in the bowels of Java:
  public boolean equals(Object that) { return this == that; }
If you want equals to do something smarter, you have to write it yourself (“overriding the version inherited from Object”). That's what class String does, which is why equals works for Strings.

Similar for Robots (and evilCopy); Draw the picture:
  Robot r1, r2, r3, r4;
  r1 = new Robot("cell phone",true,true);
  r2 = new Robot("cell phone",true,true);
  r3 = r2;
  r4 = r2.evilCopy();

three things extending Object120 gave us:


1 Note that there is a third meaning to “.” in Java: giving a full (package) name.
Exercise: explain what each “.” means in: “java.lang.System.out.print("hi")”.      

2 If you really want to know, you should make your equals take in any Object, not just a Robot. But then before checking the fields, you must make sure the Object passed in really was a Robot:

  // Inside class Robot:
  public boolean equals(Object that) {
    if (that == null || that.class != this.class) {
      return false;
    }
    else {
      // Now, compare each field of `this` and `that`
      ⋮
    }
  }
      
(You must declare equals as public.) Note that “that.class” looks like a field access, but it's not -- it's a special pseudofield added by Java mostly just so that you can write equals easily.      

homeinfolectslabsexamshws
tutor/PIsObject120 + its docsjava.lang docsjava.util docs


©2010, Ian Barland, Radford University
Last modified 2010.Oct.21 (Thu)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme