gpt4 book ai didi

java - 如何更改使用父类(super class)的此方法的输出

转载 作者:行者123 更新时间:2023-12-01 10:40:19 25 4
gpt4 key购买 nike

嗨,我想知道如何更改显示方法的输出,因此输出当前如下所示:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com