Java Reference
In-Depth Information
Code 8.1
Source code of the
MessagePost class
else {
return seconds + " seconds ago" ;
Some details are worth mentioning briefly:
Some simplifications have been made. For example, comments for a post are stored as
strings. In a more complete version, we would probably use a custom class for comments, as
comments also have additional detail such as an author and a time. The “like” count is stored
as a simple integer. We are currently not recording which user liked a post. While these sim-
plifications make our prototype incomplete, they are not relevant for our main discussion
here, and we shall leave them as they are for now.
The time stamp is stored as a single number, of type long . This reflects common practice. We
can easily get the system time from the Java system, as a long value in milliseconds. We have
also written a short method, called timeString , to convert this number into a relative time
string, such as “5 minutes ago.” In our final application, the system would have to use real time
rather than system time, but again, system time is good enough for our prototype for now.
Note that we do not intend right now to make the implementation complete in any sense. It
serves to provide a feel for what a class such as this might look like. We will use this as the
basis for our following discussion of inheritance.
Now let us compare the MessagePost source code with the source code of class PhotoPost ,
shown in Code 8.2. Looking at both classes, we quickly notice that they are very similar. This is
not surprising, because their purpose is similar: both are used to store information about news-
feed posts, and the different types of post have a lot in common. They differ only in their details,
such as some of their fields and corresponding accessors and the bodies of the display method.
Code 8.2
Source code of the
PhotoPost class
import java.util.ArrayList;
* This class stores information about a post on a social network.
* The main part of the post consists of a photo and a caption.
* Other data such as author and time are also stored.
* @author Michael Kölling and David J. Barnes
* @version 0.1
public class PhotoPost
private String username; // username of the post's author
private String filename; // the name of the image file
Search WWH ::

Custom Search