Java Reference
In-Depth Information
Code 4.10
continued
The
Auction
class
else
{
System.out.println(
"Lot number: "
+ lotNumber +
" does not exist."
);
return
null
;
}
}
}
The
lots
field is an
ArrayList
used to hold the lots offered in this auction. Lots are entered
in the auction by passing a simple description to the
enterLot
method. A new lot is created by
passing the description and a unique lot number to the constructor of
Lot
. The new
Lot
object
is added to the collection. The following sections discuss some additional, commonly found
features illustrated in the
Auction
class.
4.14.5 Anonymous objects
The
enterLot
method in
Auction
illustrates a common idiom—anonymous objects. We see
this in the following statement:
lots.add(new Lot(nextLotNumber, description));
Here, we are doing two things:
■
We are creating a new
Lot
object.
■
We are also passing this new object to the
ArrayList
's
add
method.
We could have written the same statement in two lines, to make the separate steps more explicit:
Lot furtherLot = new Lot(nextLotNumber, description);
lots.add(furtherLot);
Both versions are equivalent, but if we have no further use for the
furtherLot
variable, then
the original version avoids defining a variable with such a limited use. In effect, we create
an anonymous object—an object without a name—by passing it straight to the method that
uses it.
Exercise 4.47
The
makeABid
method includes the following two statements:
Bid bid = new Bid(bidder, value);
boolean successful = selectedLot.bidFor(bid);
The
bid
variable is only used here as a placeholder for the newly created
Bid
object before it
is passed immediately to the lot's
bidFor
method. Rewrite these statements to eliminate the
bid variable by using an anonymous object as seen in the
enterLot
method.
Search WWH ::
Custom Search