Object.toString()方法详解
Object类是所有类的父类,位于java.lang包中,是所有类的根。
toString()是其中一个常用方法,也是在开发中经常使用的一个方法。
平时我们如果在控制台直接打印输出一个对象的实例时,其实调用的就是Object类的toString()方法。
类可以实现toString方法,在控制台中打印一个对象会自动调用对象类的toString方法,所以我们可以实现自己的toString方法在控制台中显示关于类的有用信息。
Date now = new Date(); System.out.println("now = " + now);//相当于下一行代码 System.out.println("now = " + now.toString());
在java中任何对象都会继承Object对象,所以一般来说任何对象都可以调用toString这个方法。这是采用该种方法时,常派生类会覆盖Object里的toString()方法。
但是在使用该方法时必须要注意,必须要保证Object不能是null值,否则将抛出NullPointerException异常。
JDK源码:
1 /** 2 * Returns a string representation of the object. In general, the 3 * {@code toString} method returns a string that 4 * "textually represents" this object. The result should 5 * be a concise but informative representation that is easy for a 6 * person to read. 7 * It is recommended that all subclasses override this method. 8 * <p> 9 * The {@code toString} method for class {@code Object} 10 * returns a string consisting of the name of the class of which the 11 * object is an instance, the at-sign character `{@code @}', and 12 * the unsigned hexadecimal representation of the hash code of the 13 * object. In other words, this method returns a string equal to the 14 * value of: 15 * <blockquote> 16 * <pre> 17 * getClass().getName() + '@' + Integer.toHexString(hashCode()) 18 * </pre></blockquote> 19 * 20 * @return a string representation of the object. 21 */ 22 public String toString() { 23 return getClass().getName() + "@" + Integer.toHexString(hashCode()); 24 }
在进行String类与其他类型的连接操作时,自动调用toString()方法
当我们打印一个对象的引用时,实际是默认调用这个对象的toString()方法
当打印的对象所在类没有重写Object中的toString()方法时,默认调用的是Object类中toString()方法。
当我们打印对象所 在类重写了toString(),调用的就是已经重写了的toString()方法,一般重写是将类对象的属性信息返回。