Java Reference
In-Depth Information
To make this method more useful, we would typically override it in our own classes. We can,
for example, define the Post ' s display method in terms of a call to its toString method. In
this case, the toString method would not print out the details, but just create a string with the
text. Code 9.3 shows the changed source code.
Code 9.3
toString method
for Post and
MessagePost
public class Post
{
... ..
public String toString()
{
String text = username + "\n" + timeString(timestamp);
if (likes > 0) {
text += " — " + likes + " people like this.\n" ;
}
else {
text += "\n" ;
}
if (comments.isEmpty()) {
return text + " No comments.\n" ;
}
else {
return text + " " + comments.size() +
" comment(s). Click here to view.\n" ;
}
}
public void display()
{
System.out.println(toString());
}
}
public class MessagePost extends Post
{
...
public String toString()
{
return super .toString() + message + "\n" ;
}
public void display()
{
System.out.println(toString());
}
}
 
Search WWH ::




Custom Search