Java Reference
In-Depth Information
When you use the method equals to compare two objects of the class DateFourth-
Try , one object is the calling object and the other object is the argument, like so:
date1.equals(date2)
or equivalently
date2.equals(date1)
Because the method equals returns a value of type boolean , you can use an invoca-
tion of equals as the Boolean expression in an if-else statement, as shown in Display
4.8. Similarly, you can also use it anyplace else that a Boolean expression is allowed.
There is no absolute notion of “equality” that you must follow in your definition
of equals . You can define the method equals any way you wish, but to be useful, it
should reflect some notion of “equality” that is useful for the software you are
Display 4.8 Using the Methods equals and toString
1 public class EqualsAndToStringDemo
2{
3
public static void main(String[] args)
4
{
5
DateFourthTry date1 = new DateFourthTry(),
6
date2 = new DateFourthTry();
7
date1.setDate(6, 17, 1882);
These are equivalent to
date1.toString() .
8
date2.setDate(6, 17, 1882);
9
if (date1.equals(date2))
10
System.out.println(date1 + " equals " + date2);
11
else
12
System.out.println(date1 + " does not equal " + date2);
13
date1.setDate(7, 28, 1750);
These are equivalent to
date2.toString() .
14
if (date1.precedes(date2))
15
System.out.println(date1 + " comes before " + date2);
16
else
17
System.out.println(date2 + " comes before or is equal to "
18
+ date1);
19
}
20
}
Sample Dialogue
June 17, 1882 equals June 17, 1882
July 28, 1750 comes before June 17, 1882
 
Search WWH ::




Custom Search