A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

©   /  2018-11-14 17:07  /  648 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

如果不调用toString方法,直接打印对象时,打印的是对象的地址值
[Java] 纯文本查看 复制代码
package ToStringTest;

public class Test {
    public static void main(String[] args) {
        Student student=new Student("Jack");
        System.out.println(student);
    }
}

class Student {
    private String name;

    public Student(String name) {
        this.name = name;
    }
}

[Java] 纯文本查看 复制代码
/**
     * Prints an Object and then terminate the line.  This method calls
     * at first String.valueOf(x) to get the printed object's string value,
     * then behaves as
     * though it invokes <code>{@link #print(String)}</code> and then
     * <code>{@link #println()}</code>.
     *
     * @param x  The <code>Object</code> to be printed.
     */
    public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }


}


[Java] 纯文本查看 复制代码
/**
     * Returns the string representation of the {@code Object} argument.
     *
     * @param   obj   an {@code Object}.
     * @return  if the argument is {@code null}, then a string equal to
     *          {@code "null"}; otherwise, the value of
     *          {@code obj.toString()} is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }


通过以上代码,我们可以看到不调用toString方法打印student对象时,在底层依然调用了“toString()”方法。所以此处更恰当地描述应为“不重写‘toString()’方法时,打印的是地址值”。另外重写之后打印时,也就无需再写“toString()”了,因为在底层会调。



回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马