Java Reference
In-Depth Information
Ultimately, we would plan on removing the display methods completely from these classes. A
great benefit of defining just a toString method is that we do not mandate in the Post classes
what exactly is done with the description text. The original version always printed the text to
the output terminal. Now, any client (e.g., the NewsFeed class) is free to do whatever it chooses
with this text. It might show the text in a text area in a graphical user interface; save it to a file;
send it over a network; show it in a web browser; or, as before, print it to the terminal.
The statement used in the client to print the post could now look as follows:
In fact, the System.out.print and System.out.println methods are special in this
respect: if the parameter to one of the methods is not a String object, then the method auto-
matically invokes the object's toString method. Thus we do not need to write the call explic-
itly and could instead write
Now consider the modified version of the show method of class NewsFeed shown in Code 9.4.
In this version, we have removed the toString call. Would it compile and run correctly?
Code 9.4
New version of
NewsFeed show
public class NewsFeed
// fields, constructors, and other methods omitted
* Show the news feed. Currently: print the news feed details
* to the terminal. (To do: replace this later with display
* in web browser.)
public void show()
for (Post post : posts) {
In fact, the method does work as expected. If you can explain this example in detail, then you
probably already have a good understanding of most of the concepts that we have introduced in
this and the previous chapter! Here is a detailed explanation of the single println statement
inside the loop.
The for-each loop iterates through all posts and places them in a variable with the static type
Post . The dynamic type is either MessagePost or PhotoPost .
Because this object is being printed to System.out and it is not a String , its toString
method is automatically invoked.
Invoking this method is valid only because the class Post (the static type!) has a toString
method. (Remember: Type checking is done with the static type. This call would not be
Search WWH ::

Custom Search