如何在课堂上支持println? [英] How can I support println in a class?

查看:190
本文介绍了如何在课堂上支持println?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了让 println()打印,我自己制作的课程需要支持什么?例如,我有:

What does my own made class need to support in order for println() to print it? For example, I have:

public class A {
...
}

A 的哪些方法必须使此代码有效?也许是这样的:

What methods should class A have to make this code work? Maybe something like this:

public static void main() {
    A a = new A();
    System.out.println(a);
}

我猜测 toString()方法必须重载。我对吗?这够了吗?

I have a guess that the toString() method must be overloaded. Am I right? Is this enough?

推荐答案

您可以使用 System.out.println(Object) 。这个重载版本的println将打印出对象的 toString 表示。如果要自定义要打印的内容,则必须覆盖 Object#toString() 方法,例如:

You can print any Object using System.out.println(Object). This overloaded version of println will print out toString representation of your object. If you want to customize what will be printed out, you must override the Object#toString() method, for example:

public class A {
    private String foo;

    @Override
    public String toString() {
        // When you print out instance of A, value of its foo
        // field will be printed out
        return foo;
    }
}

如果你不覆盖 Object#toString()方法,将使用来自 Object 的默认实现,该类具有此形式(类名和十六进制表示形式)实例哈希码):

If you don't override the Object#toString() method, default implementation from Object class will be used, which has this form (class name and the hexidecimal representation of the instance hash code):

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

奖金:如果您需要创建 toString()从多个字段实现,有一些工具可以让它更容易。例如, ToStringBuilder 。或者像IntelliJ IDEA这样的Java IDE甚至可以根据类的字段为你生成 toString

Bonus: if you need to create toString() implementation from multiple fields, there are tools to make it easier. For instance ToStringBuilder from Commons Lang. Or some Java IDEs like IntelliJ IDEA even offer to generate toString for you based on the class' fields.

这篇关于如何在课堂上支持println?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆