嗨,我想知道如何更改显示方法的输出,因此输出当前如下所示:
Leonardo da Vinci
40 seconds ago - 2 people like this.
No comments.
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
可以做成这样
Leonardo da Vinci
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
40 seconds ago - 2 people like this.
No comments.
这两个方法,负责父类(super class)中的部分输出
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());
}
这就是子类中的两个方法,通过调用上面的父类(super class)来完成输出。
public String toString()
{
return super.toString() + message + "\n";
}
/**
* 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(toString());
}
最佳答案
这是您期望的结果:
Leonardo da Vinci
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
40 seconds ago - 2 people like this.
No comments.
消息
的值为:
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
以及 super.toString()
的值:
40 seconds ago - 2 people like this.
No comments.
您的子类 toString() 返回以下内容:
public String toString()
{
return super.toString() + message + "\n";
}
你的结果是:super.toString():
Leonardo da Vinci
40 seconds ago - 2 people like this.
No comments.
和消息
:
Had a great idea this morning.
But now I forgot what it was. Something to do with flying...
你明白为什么要按这个顺序打印吗? 您只需将顺序更改为:
return message + super.toString() + "\n";
这将更改其显示顺序。
并将 super.toString()
中的 username
值打印在变量 message
关于java - 如何更改使用父类(super class)的此方法的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34455159/