Java Reference
In-Depth Information
Make = Toyota
Model = Camry
Number of doors = 4
Make = Mazda
Model = RX-8
Number of doors = 2
When an instance method is invoked, Java passes a hidden argument to the method
(astheleftmostargumentinalistofarguments).Thisargumentisthereferencetothe
objectonwhichthemethodisinvoked,andisrepresentedatthesourcecodelevelvia
reserved word this . You don't need to prefix an instance field name with “ this.
fromwithinthemethodwheneveryouattempttoaccessaninstancefieldnamethatisn't
also the name of a parameter because “ this. ” is assumed in this situation.
METHOD-CALL STACK
Methodinvocationsrequirea method-call stack (alsoknownasa method-invocation
stack ) to keep track of the statements to which execution must return. Think of the
method-callstackasasimulationofapileofcleantraysinacafeteria—you pop (re-
move)thecleantrayfromthetopofthepileandthedishwasherwill push (insert)the
next clean tray onto the top of the pile.
Whenamethodisinvoked,theJVMpushesitsargumentsandtheaddressofthefirst
statementtoexecutefollowingtheinvokedmethodontothemethod-callstack.The
JVM also allocates stack space for the method's local variables. When the method
returns, the JVM removes local variable space, pops the address and arguments off
the stack, and transfers execution to the statement at this address.
Chaining Together Instance Method Calls
Twoormoreinstancemethodcallscanbechainedtogetherviathememberaccessoper-
ator,whichresultsinmorecompactcode.Toaccomplishinstancemethodcallchaining,
youneedtore-architectyourinstancemethodssomewhatdifferently,as Listing2-10 re-
veals.
Listing 2-10. Implementing instance methods so that calls to these methods can be chained to-
gether
class SavingsAccount
{
 
Search WWH ::




Custom Search