Java Reference
In-Depth Information
DogOwner Bob = new DogOwner();
Dog myDog;
myDog = Bob.getDog();
myDog.bark();
If you needed to reference myDog for only this one method call, then you
could avoid creating the new reference variable, myDog, by concatenating the
method calls, using the following code
Bob.getDog().bark();
To understand what happens in a concatenated method call, read the code
from left to right, starting with the object reference and first method. Determine
the type of data returned, which must be a reference to an object. Using that
object type reference, read the next method call, which is a method of the
referenced object.
Thus, in the above code example, the line of code first would use Bob, a
DogOwner object, to call getDog(), which returns a reference to a Dog object.
This reference is used implicitly to call its bark() method. Although Bob (the
DogOwner object) does not have a bark() method, the returned reference to a
Dog object does.
Understanding Concatenated Method Calls
You can understand what happens in a concatenated method call
by first reading from the left only the object reference and first
method. Determine the type of data returned. It must be a refer-
ence to an object. Using that object type, read the next method
call, and so forth, until the last method is called.
In this chapter, the same technique is used to invoke the resetCount()
method from a newly created PasswordInvalidException object in the validate()
method of the Password class. Figure 10-33 displays the code for the chained
method call in the validate() method of the Password class. The line of code first
includes a constructor to create a PasswordInvalidException object. Once the
object is created, the reference is used to call the resetCount() method of the
PasswordInvalidException object.
195
new PasswordInvalidException () .resetCount () ; // resets count of invalid exceptions
FIGURE 10-33
Search WWH ::




Custom Search