Java Reference
In-Depth Information
To correctly rewrite the method setDate , we need some way to say “the instance
variable month ” as opposed to the parameter month . The way to say “the instance vari-
able month ” is this.month . Similar remarks apply to the other two parameters. So, the
correct rewriting of the method setDate is as follows:
public void setDate( int month, int day, int year)
{
this .month = monthString(month);
this .day = day;
this .year = year;
}
This version is completely equivalent to the version in Display 4.4.
Self-Test Exercises
10. The method writeOutput in Display 4.2 uses the instance variables month , day ,
and year , but gives no object name for these instance variables. Every instance
variable must belong to some object. To what object or objects do these instance
variables in the definition of writeOutput belong?
11. Rewrite the definitions of the methods getDay and getYear in Display 4.2 using
the this parameter.
12. Rewrite the method getMonth in Display 4.2 using the this parameter.
Methods That Return a Boolean Value
There is nothing special about methods that return a value of type boolean . The type
boolean is a primitive type, just like the types int and double . A method that returns
a value of type boolean must have a return statement of the form
return Boolean_Expression ;
So, an invocation of a method that returns a value of type boolean returns either
true or false . It thus makes sense to use an invocation of such a method to control
an if-else statement, to control a while loop, or anyplace else that a Boolean
expression is allowed. Although there is nothing new here, people who have not
used boolean valued methods before sometimes find them to be uncomfortable. So
we will go through one small example.
The following is a method definition that could be added to the class DateThirdTry
in Display 4.4:
public boolean isBetween( int lowYear, int highYear)
{
return ( (year > lowYear) && (year < highYear) );
}
Search WWH ::




Custom Search