/** * Inheritance Example * socialnetwork Module * Source code file: Post.java * * This class stores information about a news feed post in a * social network. Posts can be stored and displayed. This class * serves as a superclass for more specific post types. * Javadoc comments are used * * Source: Objects First with Java * @author Michael Koelling and David J. Barnes * @version 0.3 */ import java.util.ArrayList; public class Post { // username of the post's author private String _username; private long _timestamp; private int _likes; private ArrayList _comments; /** * Constructor for objects of class Post. * * @param author The username of the author of this post. */ public Post(String author) { _username = author; _timestamp = System.currentTimeMillis(); _likes = 0; _comments = new ArrayList(); } /** * Record one more 'Like' indication from a user. */ public void like() { _likes++; } /** * Record that a user has withdrawn his/her 'Like' vote. */ public void unlike() { if (_likes > 0) { _likes--; } } /** * Add a comment to this post. * * @param text The new comment to add. */ public void addComment(String text) { _comments.add(text); } /** * Return the time of creation of this post. * * @return The post's creation time, as a system time value. */ public long getTimeStamp() { return _timestamp; } /** * Display the details of this post. * * (Currently: Print to the text terminal. This is simulating display * in a web browser for now.) */ public void display() { System.out.println(_username); System.out.print(timeString(_timestamp)); if(_likes > 0) { System.out.println(" - " + _likes + " people like this."); } else { System.out.println(); } if(_comments.isEmpty()) { System.out.println(" No comments."); } else { System.out.println(" " + _comments.size() + " comment(s). Click here to view."); } } /** * Create a string describing a time point in the past in terms * relative to current time, such as "30 seconds ago" or "7 minutes ago". * Currently, only seconds and minutes are used for the string. * * @param time The time value to convert (in system milliseconds) * @return A relative time string for the given time */ private String timeString(long time) { long _current = System.currentTimeMillis(); long _pastMillis = _current - time; // time passed in milliseconds long _seconds = _pastMillis/1000; long _minutes = _seconds/60; if(_minutes > 0) { return _minutes + " minutes ago"; } else { return _seconds + " seconds ago"; } } }