Java Reference
In-Depth Information
9.6
Method polymorphism
What we have just discussed in the previous sections (Sections 9.2-9.5) is yet another form of
polymorphism. It is what is known as
polymorphic method dispatch
(or
method polymorphism
for short).
Concept:
Method polymor-
phism.
Method
calls in Java are
polymorphic. The
same method call
may at different
times invoke dif-
ferent methods,
depending on the
dynamic type of
the variable used to
make that call.
Remember that a polymorphic variable is one that can store objects of varying types (every
object variable in Java is potentially polymorphic). In a similar manner, Java method calls are
polymorphic, because they may invoke different methods at different times. For instance, the
statement
post.display();
could invoke the
MessagePost
's
display
method at one time and the
PhotoPost
's
dis-
play
method at another, depending on the dynamic type of the
post
variable.
9.7
Object methods:
toString
In Chapter 8, we mentioned that the universal superclass,
Object
, implements some methods
that are then part of all objects. The most interesting of these methods is
toString
, which we
introduce here (if you are interested in more detail, you can look up the interface for
Object
in
the standard library documentation).
Concept:
Exercise 9.4
Look up
toString
in the library documentation. What are its parameters?
What is its return type?
Every object in Java
has a
toString
method that can
be used to return
a
string
repre-
sentation of itself.
Typically, to make
it useful, an object
should override this
method.
The purpose of the
toString
method is to create a string representation of an object. This is
useful for any objects that are ever to be textually represented in the user interface, but also helps
for all other objects; they can then easily be printed out for debugging purposes, for instance.
The default implementation of
toString
in class
Object
cannot supply a great amount of detail.
If, for example, we call
toString
on a
PhotoPost
object, we receive the string similar to this:
PhotoPost@6acdd1
The return value simply shows the object's class name and a magic number.
2
Exercise 9.5
You can easily try this out. Create an object of class
PhotoPost
in your
project, and then invoke the
toString
method from the
Object
submenu in the object's
pop-up menu.
2
The magic number is in fact the memory address where the object is stored. It is not very useful except
to establish identity. If this number is the same in two calls, we are looking at the same object. If it is
different, we have two distinct objects.
Search WWH ::
Custom Search