Java中继承toString方法_java中toString方法详解

1、Object类中定义有toString方法,用于返回对象的字符串表示(一个可以表示该对象属性内容的字符串),返回的字符串形式为 “类名@hashCode值”。下面看Object类中的源码:

public String toString() {

return getClass().getName() + "@" + Integer.toHexString(hashCode());

}

根据源码可知,返回值是:类名+符号@+对象的哈希码值。  在源码的注释中有重要一句话:It is recommended that all subclasses override this method(建议所有的子类都覆盖这个方法),java类根据需要重写toString方法才能使返回值更有意义。

2、不重写toString方法,例子如下:

public class DemoApplicationTests {

public static void main (String[] args){

Point p = new Point(1,2);

System.out.println(p.toString());

}

}

class Point{

private int x;

private int y;

public Point(int x, int y){

this.x = x;

this.y = y;

}

}

输出结果(类名+符号@+对象的哈希码值):

Point@6267c3bb 3、重写toString方法,例子如下:

public class DemoApplicationTests {

public static void main (String[] args){

Point p = new Point(1,2);

System.out.println(p.toString());

}

}

class Point{

private int x;

private int y;

public Point(int x, int y){

this.x = x;

this.y = y;

}

//重写toString方法

public String toString(){

return "x=" + x + ",y=" + y;

}

}

输出结果(根据需要输入字符串):

x=1,y=2 4、上面的两个例子中  : System.out.println(p.toString()); 可以简写为  :                 System.out.println(p); 因为System.out.println方法会自动调用对象的toString方法,将返回的字符串输出。

5、下面再看一个String类的例子:

public static void main (String[] args){

String str = new String("Hello");

System.out.println(str);

}

输出结果:

Hello 那么我们没有重写toString方法,为什么输出的结果不是 “类名+符号@+对象的哈希码” 形式,而是一个字符串呢。  这是因为String已经替我们重写了toString方法,直接返回字符串本身,下面看String类只中的源码:

/**

* This object (which is already a string!) is itself returned.

*

* @return  the string itself.

*/

public String toString() {

return this;

}

总结:

toString方法在Object类中定义,因为Java中每个类都默认继承Object类,所以每个类都具有toString方法,作用是返回对象的字符串表示(类名+符号@+对象的哈希码)。 为了使返回值更有意义,所以常用的类都已经重写了toString方法,如String类、Date类。我们自己写的类也建议重写toString方法。 ---------------------  作者:暴力丶白菜  来源:CSDN  原文:https://blog.csdn.net/Echo_width/article/details/79711540


版权声明:本文为weixin_39675679原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。