[Bluej-discuss] chained method calls
Stephen Bloch
sbloch at adelphi.edu
Wed Jun 21 03:39:14 BST 2006
JD <dnaltrop at gmail.com> wrote:
>The following line of code gave me the most grief until I got it working.
>
>highestBid.getBidder().getName();
>
>It is an object reference to a method to another object to a method within
>the object referenced by the getBidder() method!?!?!? It works. But what
>the heck did I create here? What is it called? Have we covered this type
>of construction in the book yet and I missed it?
>... I didnt know you could call a local object reference
>highestBid that calls another object reference getBidder() in an external
>class Bid that calls another object reference bidder in another external
>class Person that FINALLY calls a real method getName that returns the
>bidders person name....whew!.... I hope this book explores more examples of
>these chained external method calls as I am sure they are common to use.
It's really nothing special. If you're allowed to compute 3+4, and
you're allowed to compute 7*2, who's to say you CAN'T compute (3+4)*2
? 3 and 4 are both numbers, so it's legitimate to apply + to them,
and the result is a number, as is 2, so it's legitimate to apply * to
them.
Likewise, highestBid is a variable of type Bid (or whatever), so it's
legitimate to call the getBidder() method on it. That method returns
a Person (or whatever), so the whole expression
"highestBid.getBidder()" can be said to be of type Person, so it's
legitimate to call the getName() method on it.
Here's how it would sound in my classroom:
I highlight the variable name "highestBid". "What type is this?"
Somebody (I hope) answers "It's a Bid".
"How do you know?"
"Because highestBid is DECLARED as a Bid on line [whatever]."
"Good. Now what are we doing to highestBid?"
"Calling the getBidder() method."
"Is that a method that can be called on objects of type Bid?"
"Yes."
"How do you know?"
"Because the getBidder() method is defined in between the
curly-braces of the Bid class."
I highlight the whole expression "highestBid.getBidder()". "What
type is this?"
"It's a Person."
"How do you know?"
"Because the getBidder() method has a return type of Person."
"Good. Now what are we doing to highestBid.getBidder()?"
"Calling the getName() method."
"Is that a method that can legally be called on objects of type Person?"
"Yes"
"How do you know?"
etc. etc.
Eventually my students get really really sick of me asking "What type
is this?" and "How do you know?" If I've done my job right, they
start asking themselves the same questions to save time.
--
Stephen Bloch
sbloch at adelphi.edu
More information about the bluej-discuss
mailing list