Java Reference
In-Depth Information
Consider the following lines of code:
DateThirdTry date =
new
DateThirdTry();
date.setDate(1, 2, 3001);
if
(date.isBetween(2000, 4000))
System.out.println(
"The date is between the years 2000 and 4000");
else
System.out.println(
"The date is not between the years 2000 and 4000");
The expression
date.isBetween(2000,
4000)
is an invocation of a method that returns
a
boolean
value—that is, returns one of the two values
true
and
false
. So, it makes
perfectly good sense to use it as the controlling Boolean expression in an
if-else
state-
ment. The expression
year
in the definition of
isBetween
really means
this.year
, and
this
stands for the calling object. In
date.isBetween(2000, 4000)
the calling object is
date
. So, this returns the value
(date.year > lowYear) && (date.year < highYear)
But,
2000
and
4000
are plugged in for the parameters
lowYear
and
highYear
, respec-
tively. So, this expression is equivalent to
(date.year > 2000) && (date.year < 4000)
Thus, the
if-else
statement is equivalent to
4
if
((date.year > 2000) && (date.year < 4000))
System.out.println(
"The date is between the years 2000 and 4000.");
else
System.out.println(
"The date is not between the years 2000 and 4000.");
Thus, the output produced is
The date is between the years 2000 and 4000.
Another example of a
boolean
valued method, which we will, in fact, add to our
date class, is shown below:
public boolean
precedes(DateFourthTry otherDate)
{
return
( (year < otherDate.year) ||
4
Later in this chapter, we will see that because
year
is marked
private
, it is not legal to write
date.year
in a program, but the meaning of such an expression is clear even if you cannot include it in a program.