Java Reference
In-Depth Information
designing. A common way to define
equals
for simple classes of the kind we are
looking at now is to say
equals
returns
true
if each instance variable of one object
equals the corresponding instance variable of the other object. This is how we
defined
equals
in Display 4.7.
If the definition of
equals
in Display 4.7 seems less than clear, it may help to
rewrite it as follows using the
this
parameter:
public boolean
equals(DateFourthTry otherDate)
{
return
( ((
this
.month).equals(otherDate.month))
&& (
this
.day == otherDate.day) && (
this
.year == otherDate.year) );
}
So if
date1
and
date2
are objects of the class
DateFourthTry
, then
date1.equals
(date2)
returns
true
provided the three instance variables in
date1
have values that
are equal to the three instance variables in
date2
.
Also, note that the method in the definition of
equals
that is used to compare months
is not the
equals
for the class
DateFourthTry
but the
equals
for the class
String
. You
know this because the calling object, which is
this.month
, is of type
String
.
(Remember that we use the
equals
method of the class
String
because
==
does not
work correctly for comparing
String
values. This was discussed in the Pitfall section of
Chapter 3 entitled “Using
==
with Strings.”)
In Chapter 7, you will see that there are reasons to make the definition of the
equals
method a bit more involved. But the spirit of what an
equals
method should
be is very much like what we are now doing, and it is the best we can do with what we
know so far.
The method
toString
should be defined so that it returns a
String
value that rep-
resents the data in the object. One nice thing about the method
toString
is that it
makes it easy to output an object to the screen. If
date
is of type
DateFourthTry
, then
you can output the date to the screen as follows:
toString
System.out.println(date.toString());
In fact, S
ystem.out.println
was written so that it automatically invokes
toString()
if
you do not include it. So, the object
date
can also be output by the following simpler
and equivalent statement:
println
used
with objects
System.out.println(date);
This means that the method
writeOutput
in Display 4.7 is superfluous and could
safely be omitted from the class definition.
If you look at Display 4.8, you will see that
toString
is also called automatically
when the object is connected to some other string with a +, as in
System.out.println(date1 + " equals " + date2);