Page 260 - Introduction to Programming with Java: A Problem Solving Approach
P. 260

                226
Chapter 6 Object-Oriented Programming
public void setPercentGrowthRate(double percentGrowthRate)
{
}
// end setPercentGrowthRate
if (percentGrowthRate < -100)
{
}
else
{
}
System.out.println("Attempt to assign an invalid growth rate.");
this.percentGrowthRate = percentGrowthRate;
Our examples will occasionally include some mutator error checking to illustrate this filtering function, but to reduce clutter we’ll usually employ the minimal form.
Boolean Methods
A Boolean method checks to see whether some condition is true or false. If the condition is true, then true is returned. If the condition is false, then false is returned. To accommodate the boolean returned value, Boolean methods must always specify a boolean return type. A Boolean method name should normally start with “is.” For example, here’s an isAdolescent method that determines whether a Mouse object is an adolescent by comparing its age value to 100 days:
            Apago PDF Enhancer
if (this.age <= 100)
public boolean isAdolescent()
{
}
// end isAdolescent
{
}
else
{
}
return true;
return false;
Here’s how this code might be shortened: public boolean isAdolescent()
{
return this.age <= 100;
} // end isAdolescent
To show how the shortened method works, we’ll plug in sample values. But first, let’s get settled on the goal: Whenever age is less than or equal to 100, we want the method to return true to indicate adoles- cence. If age is 50, what is returned? true (Because the return statement’s this age <= 100 ex- pression evaluates to true.) If age is 102, what is returned? false (Because the return statement’s
100 expression evaluates to false.) Plug in any number for age and you’ll see that the shortened function does indeed work properly. In other words, the shortened isAdolescent method does indeed return true whenever age is less than or equal to 100.
this age <=






























































   258   259   260   261   262