Java Reference
In-Depth Information
Code 4.9
Handle a bid for a lot
* Attempt to bid for this lot. A successful bid
* must have a value higher than any existing bid.
* @param bid A new bid.
* @return true if successful, false otherwise
public boolean bidFor(Bid bid)
if (highestBid == null ) {
// There is no previous bid.
highestBid = bid;
return true ;
else if (bid.getValue() > highestBid.getValue()) {
// The bid is better than the previous one.
highestBid = bid;
return true ;
else {
// The bid is not better.
return false ;
Other methods omitted.
Here, we first check whether this bid is the highest bid. This will be the case if there has been
no previous bid or if the current bid is higher than the best bid so far. The first part of the check
involves the following test:
highestBid == null
This is a test for whether the highestBid variable is currently referring to an object or not.
As described in the previous section, until a bid is received for this lot, the highestBid field
will contain the null value. If it is still null , then this is the first bid for this particular lot and
it must clearly be the highest one. If it is not null , then we have to compare its value with the
new bid. Note that the failure of the first test gives us some very useful information: we now
know for sure that highestBid is not null , so we know that it is safe to call a method on it.
We do not need to make a null test again in this second condition. Comparing the values of the
two bids allows us to choose a higher new bid or reject the new bid if it is no better.
4.14.4 The Auction class
The Auction class (Code 4.10) provides further illustration of the ArrayList and for-each
loop concepts we discussed earlier in the chapter.
Search WWH ::

Custom Search