|
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs
Review: Non-static methods:
Song s1 = new Song( "Violet Hill", "Coldplay", 180, true ); // Instead of fitsOnDisk(s1,2.5), write: s1.fitsOnDisk(2.5); |
/* Instead of: static boolean fitsOnDisk(Song thisSong, double freeSpace) { return thisSong.length * MB_PER_SEC <= freeSpace; } We will write: */ |
One common mistake:
When converting
to a non-static version, be careful to move the
If you get the error “unable to call a non-static function from a static context”, what does that mean? What is the “static context” being mentioned?
One student asked about
Similar for Robots (and evilCopy); Draw the picture:
// **Draw pictures** (memory diagrams): Robot r1, r2, r3, r4; r1 = new Robot("cell phone",true,true); r2 = new Robot("cell phone",true,true); r3 = r2; r4 = r2.evilCopy(); |
r2.isEvil = false; r2.isEvil // false, as expected. r1.isEvil // still true, as expected. r3.isEvil // false! |
Note that the same picture holds for
// **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,Equality: intensional ("equals(Object)"; if applied recursively it's a "deep" equality-check) extensional (shallow) ("==").== returnstrue 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 aequals (inherited fromjava.lang.Object ) which just does the same thing== does (?!):If you want
// Inside class java.lang.Object, deep in the bowels of Java: public boolean equals(Object that) { return this == that; }equals to do something smarter, you have to write it yourself (“overriding the version inherited fromObject ”). That's whatclass String does, which is whyequals works forString s.
Three things extending Object120 gave us:
home—info—lects—labs—exams—hws
tutor/PIs—breeze (snow day)
Object120 + its docs—java.lang docs—java.util docs
©2012, Ian Barland, Radford University Last modified 2012.Oct.17 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |