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

java之toString()方法,javatostring方法

来源: javaer 分享于  点击 7502 次 点评:7

java之toString()方法,javatostring方法


  今天重新看了一下java中的toString()方法,在默认情况下,所有的java对象都会从最高层的基类Object那里继承toString方法(Object类是java中所有类的父类)。

  1.Object.class中的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.
     * 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());
    }

  简单来说呢,toString()这个来自Object的方法将会返回getClass().getName() + "@" + Integer.toHexString(hasCode());

  也就是当前这个类的类名+十六进制的哈希值。

  举例我有一个叫Dragon的类,实例化它的对象后直接打印到控制台:

com.demo.Dragon@15db9742
  此外呢,在上面的源码中我们发现有一行:It is recommended that all subclass override this method.也就是推荐我们的每个子类都会覆盖/重载这个toString()方法。

  2.重载(Override)toString方法

  通常来说,重载toString的目的与源码中所述是类似的,是为了代表这个被实例化的对象,那么我们可以return由这个对象中的域对象组成的字符串即可。

  例如:

public class Dragon {
	long id;
	String state;
	public Dragon(long id){
		this.id=id;
		this.state="LIVE";
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		//return super.toString();
		return "id="+id
			+", state="+state;
	}
}

  3.toString方法的特殊作用

  实际上,toString()方法还有一个特殊的作用。

  首先做一个测试,把类Dragon中的覆盖的toString方法注释掉,然后实例化一个Dragon对象,System.out.println( new Dragon(1)),控制台显示如下:

com.demo.Dragon@15db9742

  诶,这个和我们上面通过调用toString方法打印出来的东西不是一样的么?难道这里直接输出对象会自动调用这个类的toString()方法?

  查看一个println方法的源码:

    public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

  喔,这里打印的字符串来自于String类的valueOf()方法:

    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

  yes,这里调用了obj.toString();

  也就是说,如果我们直接输出对象,那么System.out.println()会自动去调用这个对象的toString方法获取它的返回值,然后输出;

  是不是很有趣?

  虽然没什么卵用的感觉。。。

  

相关文章

    暂无相关文章

用户点评