java中toString方法详解

2 篇文章 0 订阅

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 

  • 18
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值