Java Reference
In-Depth Information
Now that we know about subtyping, we need to be more precise. Consider the following statement:
Vehicle v1 = new Car();
What is the type of v1 ? That depends on what precisely we mean by “type of v1 .” The type of
the variable v1 is Vehicle ; the type of the object stored in v1 is Car . Through subtyping and
substitution rules, we now have situations where the type of the variable and the type of the
object stored in it are not exactly the same.
Let us introduce some terminology to make it easier to talk about this issue:
We call the declared type of the variable the static type, because it is declared in the source
code—the static representation of the program.
The static type of
a variable v is the
type as declared in
the source code in
the variable decla-
ration statement.
We call the type of the object stored in a variable the dynamic type, because it depends on
assignments at runtime—the dynamic behavior of the program.
Thus, looking at the explanations above, we can be more precise: the static type of v1 is
Vehicle , the dynamic type of v1 is Car . We can now also rephrase our discussion about the
call to the post's display method in the NewsFeed class. At the time of the call
The dynamic type
of a variable v is
the type of the ob-
ject that is currently
stored in v .
the static type of post is Post , while the dynamic type is either MessagePost or PhotoPost
(Figure 9.3). We do not know which one of these it is, assuming that we have entered both
MessagePost and PhotoPost objects into the feed.
Figure 9.3
Variable of type Post
containing an object
of type PhotoPost
The compiler reports an error because, for type checking, the static type is used. The dynamic
type is often only known at runtime, so the compiler has no other choice but to use the static
type if it wants to do any checks at compile time. The static type of post is Post , and Post
does not have a display method. It makes no difference that all known subtypes of Post do
have a display method. The behavior of the compiler is reasonable in this respect, because it
has no guarantee that all subclasses of Post will, indeed, define a display method, and this is
impossible to check in practice.
In other words, to make this call work, class Post must have a display method, so we appear
to be back to our original problem without having made any progress.
Exercise 9.2 In your network project, add a display method in class Post again. For
now, write the method body with a single statement that prints out only the username. Then
modify the display methods in MessagePost and PhotoPost so that the MessagePost
version prints out only the message and the PhotoPost version prints only the caption. This
removes the other errors encountered above (we shall come back to those below).
Search WWH ::

Custom Search