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

标签 java inheritance subclass superclass bluej

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

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/

相关文章:

java - 当 Class 扩展 JFrame 时,httpunit 不起作用

Java 得到这个的运行时类?

swift - 如何从我的子类访问属性?

c++ - 通过删除基类来破坏派生类

c++ - 当 C++ 中的参数是父类类型时,如何调用子类的方法?

带有子类参数的Java getMethod

java - $unwind $push Mongo

java - 如何在java中检查FTP路径是否存在并且可写

java - 从 Java 游戏服务器到客户端的 TCP 和 UDP 连接

java - 避免静态字段的最佳实践