欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

Object.toString() 返回的到底是不是内存地址,

来源: javaer 分享于  点击 10236 次 点评:218

Object.toString() 返回的到底是不是内存地址,


从 java.lang.Object 原码中可以看到 toString() 方法,此方法是一个公有方法,所有的类都会继承此方法,也可以复写此方法。

    /**
     * Returns a string representation of the object. In general, the
     * {@code toString} method returns a string that
     * "textually represents" this object. The result should
     * be a concise but informative representation that is easy for a
     * person to read.
     * 返回的对象的字符串表示形式,通常情况下,toString() 方法返回一个字符串,该结果应该简洁但信息
     * 丰富,让人易于阅读。建议所有子类重写此方法。
     * It is recommended that all subclasses override this method.
     * <p>
     * The {@code toString} method for class {@code Object}
     * returns a string consisting of the name of the class of which the
     * object is an instance, the at-sign character `{@code @}', and
     * the unsigned hexadecimal representation of the hash code of the
     * object. In other words, this method returns a string equal to the
     * value of:
     * 换句话说,这个方法返回的字符串等价于 类名+@+对象的哈希码的十六进制表示
     * <blockquote>
     * <pre>
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * </pre></blockquote>
     *
     * @return  a string representation of the object.
     */
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

所以,通过查看Java API 文档,toString() 并不是 对象的内存地址,

经常有人会通过 System.out.println(yourObj) 打印出来的字符串说成是对象的内存地址,println() 内部依然是调用了 yourObj.toString() 方法,以后再有人说toString() 打印的是对象的内存地址的时候,可以直接反驳他。

相关文章

    暂无相关文章

用户点评