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

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

lect08a
object equality

Review: Non-static methods:
 - how to *call* them
 
        Song s1 = new Song( "Violet Hill", "Coldplay", 180, true );

        // Instead of   fitsOnDisk(s1,2.5), write:
        s1.fitsOnDisk(2.5);
 
- how to *write* them.
  /* Instead of:
  static boolean fitsOnDisk(Song thisSong, double freeSpace) {
    return thisSong.length * MB_PER_SEC <= freeSpace;
    }
  We will write:
  */
  static boolean fitsOnDisk( /* Song thisSong, */ double freeSpace) {
    return thisSong.length * MB_PER_SEC <= freeSpace;
    }
 
We go through our class Robot: - remove 'extends Object120' (and making fixes); - writing OO versions of willBattle, evilCopy. Beginning code: Robot.java, ending code: Robot.java. Equality: intensional ("equals(Object)"; if applied recursively it's a "deep" equality-check) extensional (shallow) ("=="). **Draw pictures** (memory diagrams): String s1, s2, s3; s1 = "election"; s2 = s1; s3 = new String("election"); s1.equals(s2) s1.equals(s3) s1 == s2 s1 == s3
What's going on: When comparing two object references, == returns true if (and only if) they reference (point to) the identically-same object.

(reached here)


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: - constructor (we fixed) - toString (override like you did for Treasure) - deep equality-test

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