Java Reference
In-Depth Information
Display 4.7
A Class with Methods equals and toString (part 2 of 2)
20
public boolean precedes(DateFourthTry otherDate)
21
{
22
return ( (year < otherDate.year) ||
23
(year == otherDate.year && getMonth() < otherDate.getMonth()) ||
24
(year == otherDate.year && month.equals(otherDate.month)
25
&& day < otherDate.day) );
26
}
<The rest of the method definitions are identical to the ones in DateThirdTry in Display 4.4.>
27
}
The return statement in the definition of the method precedes may look intimi-
dating, but it is really straightforward. It says that date1.precedes(date2) returns
true , provided one of the following three conditions is satisfied:
date1.year < date2.year
date1.year equals date2.year and date1.month comes before date2.month
date1 and date2 have the same year and month and
date1.day < date2.day.
If you give it a bit of thought, you will realize that date1 precedes date2 in time pre-
cisely when one of these three conditions is satisfied.
The Methods equals and toString
Java expects certain methods to be in all, or almost all, classes. This is because some of
the standard Java libraries have software that assumes such methods are defined. Two of
these methods are equals and toString . Therefore, you should include such methods
and be certain to spell their names exactly as we have done. Use equals , not same or
areEqual . Do not even use equal without the s . Similar remarks apply to the toString
method. After we have developed more material, we will explain this in more detail. In
particular, we will then explain how to give a better method definition for equals . For
now, just get in the habit of including these methods.
The method equals is a boolean valued method to compare two objects of the class
to see if they satisfy the intuitive notion of “being equal.” So, the heading should be
equals
public boolean equals( Class_Name Parameter_Name )
Display 4.7 contains definitions of the methods equals and toString that we might add to
our date class, which is now named DateFourthTry . The heading of that equals method is
public boolean equals(DateFourthTry otherDate)
 
Search WWH ::




Custom Search