|
home—info—lects—labs—exams—hws
tutor/PIs—Object120 + its docs—java.lang docs—java.util docs
As a class, we will
take
We will improve
We have already discussed how we might want two versions
of
But something isn't quite right;
our
The truth is:
(Okay, to be fair:
Sometimes
Rule of thumb: When you write a class, you probably want to use the default, built-inequals whenever your program will create only onenew instance corresponding to objects in the real world (e.g.Pizza s orStudent s).
Rule of thumb: When you write a class, you probably want to use the default, built-inequals whenever you have methods which update (mutate) fields.
(This often goes hand-in-hand with the previous rule.)
Rule of thumb: When you write a class, you should overrideequals if you can't conceive of two instances having the same fields, but somehow being considered different. E.g.,String orRaceResult .
Testing tip: For testing, we usually want a “deep equals” that checks each field (comparing fields for deep equality themselves). However, this might conflict with the rules-of-thumb above. One solution is to write your own methoddeepEquals (separate fromequals ), and use that in your test methods. This works fine for a single class, but becomes more complicated if you have an object whose fields are other objects.
home—info—lects—labs—exams—hws
tutor/PIs—Object120 + its docs—java.lang docs—java.util docs
©2010, Ian Barland, Radford University Last modified 2010.Oct.21 (Thu) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |