Java Reference
In-Depth Information
method. Within the body of a
void
method, this difference is reflected in the fact that there
is no return statement.
2
In the body of
insertMoney
, there is a single statement that is another form of assignment state-
ment. We always consider assignment statements by first examining the calculation on the right-hand
side of the assignment symbol. Here, its effect is to calculate a value that is the sum of the number in
the
amount
parameter and the number in the
balance
field. This combined value is then assigned
to the
balance
field. So the effect is to increase the value in
balance
by the value in
amount
.
3
Exercise 2.31
How can we tell from just its header that
setPrice
is a method and not a
constructor?
public void setPrice(int cost)
Exercise 2.32
Complete the body of the
setPrice
method so that it assigns the value of
its parameter to the
price
field.
Exercise 2.33
Complete the body of the following method, whose purpose is to add the
value of its parameter to a field named
score
.
/**
* Increase score by the given number of points.
*/
public void increase(int points)
{
...
}
Exercise 2.34
Is the increase method a mutator? If so, how could you demonstrate this?
Exercise 2.35
Complete the following method, whose purpose is to subtract the value of its
parameter from a field named
price
.
/**
* Reduce price by the given amount.
*/
public void discount(int amount)
{
...
}
2
In fact, Java does allow
void
methods to contain a special form of return statement in which there is no
return value. This takes the form
return;
and simply causes the method to exit without executing any further code.
3
Adding an amount to the value in a variable is so common that there is a special
compound assignment
operator
to do this: +=. For instance:
balance += amount;
Search WWH ::
Custom Search