Java Reference
In-Depth Information
Each of these four Dog objects looks the same in memory; however, each is
being viewed in a different form, depending on its reference. For example,
with the Dog reference fido, all the methods of Dog, Mammal, Object, and Play
can be invoked without requiring any casting of the Dog reference.
fido.sleep();
fido.playFetch();
fido.breathe();
fido.toString();
Compare this to the Mammal reference rover. Without casting, which meth-
ods can be invoked? Aside from the Object methods, only the breathe()
method can be invoked on rover:
rover.breathe();
Similarly, what methods (aside from the Object methods) can be invoked
using the Play reference spot, without casting? Because it is a Play reference,
only the two methods of Play can be invoked:
spot.playCatch();
spot.playFetch();
Using the Object reference pooch, only the methods in Object can be
invoked without casting. For example, the following code is valid.
pooch.toString();
However, to invoke any of the methods in Mammal, Play, or Dog requires
the pooch reference to be cast. For example, the following statement is valid:
((Dog) pooch).sleep();
The following FourDogs program demonstrates a Dog object taking on
these four different forms through polymorphism. Study the program, which
compiles and executes successfully, and try to determine its output, which is
shown in Figure 10.11.
public class FourDogs
{
public static void main(String [] args)
{
Search WWH ::




Custom Search