How can I support println in a class?

血红的双手。 提交于 2019-12-17 10:01:32

问题


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

public class 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);
}

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


回答1:


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;
    }
}

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());
}

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.




回答2:


You need to provide an override of toString() method for this:

public class A {
    @Override
    public String toString() {
        return "A";
    }
}

The method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.




回答3:


You need implement toString() method. Everything you return from it will be printed.



来源:https://stackoverflow.com/questions/27647567/how-can-i-support-println-in-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!