How can I support println in a class?

前端 未结 3 732
无人及你
无人及你 2020-12-02 01:07

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

public class A {
...
}

Wh

3条回答
  •  旧时难觅i
    2020-12-02 01:33

    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.

提交回复
热议问题