Java Reference
In-Depth Information
4.14.6
Chaining method calls
In our introduction to the
auction
project, we noted a chain of object references:
Auction
objects store
Lot
objects; each
Lot
object can store a
Bid
object; each
Bid
object stores a
Person
object. If the
Auction
object needs to identify who currently has the highest bid on a
Lot
, then it would need to ask the
Lot
to return the
Bid
object for that lot and then ask the
Bid
object for the
Person
who made the bid.
Ignoring the possibility of
null
object references, we might see something like the following
sequence of statement in order to print the name of a bidder:
Bid bid = lot.getHighestBid();
Person bidder = bid.getBidder();
String name = bidder.getName();
System.out.println(name);
Because the
bid
,
bidder
, and
name
variables are being used here simply as staging posts to
get to the bidder's name, it is common to see sequences like this compressed through the use of
anonymous object references. For instance, we can achieve the same effect with the following:
System.out.println(lot.getHighestBid().getBidder().getName());
This looks as if methods are calling methods, but that is not how this must be read. Bearing
in mind that the two sets of statements are equivalent, the chain of method calls must be read
strictly from left to right:
lot.getHighestBid().getBidder().getName()
The call to
getHighestBid
returns an anonymous
Bid
object, and the
getBidder
method
is then called on that object. Similarly,
getBidder
returns an anonymous
Person
object, so
getName
is called on that person.
Such chains of method calls can look complicated, but they can be unpicked if you understand
the underlying rules. Even if you choose not to write your code in this more concise fashion,
you should learn how to read it, because you may come across it in other programmers' code.
Exercise 4.48
Add a
close
method to the
Auction
class. This should iterate over the
collection of lots and print out details of all the lots. Use a for-each loop. Any lot that has had at
least one bid for it is considered to be sold, so what you are looking for is
Lot
objects whose
highestBid
field is not
null
. Use a local variable inside the loop to store the value returned
from calls to the
getHighestBid
method, and then test that variable for the
null
value.
For lots with a bidder, the details should include the name of the successful bidder and the
value of the winning bid. For lots with no bidder, print a message that indicates this.
Exercise 4.49
Add a
getUnsold
method to the
Auction
class with the following header:
public ArrayList<Lot> getUnsold()
This method should iterate over the
lots
field, storing unsold lots in a new
ArrayList
local
variable. What you are looking for is
Lot
objects whose
highestBid
field is
null
. At the end
of the method, return the list of unsold lots.
Search WWH ::
Custom Search