toString方法

toString方法

1.源代码

public String toString()

返回对象的字符串表示形式。 一般来说, toString方法返回一个“textually代表”这个对象的字符串。 结果应该是一个简明扼要的表达,容易让人阅读。 建议所有子类覆盖此方法。

该toString类方法Object返回一个由其中的对象是一个实例,该符号字符`的类的名称的字符串@ ”和对象的哈希码的无符号的十六进制表示。 换句话说,这个方法返回一个等于下列值的字符串:

     getClass().getName() + '@' + Integer.toHexString(hashCode());
     

}

2.toString方法为什么要重写

package com.shouyeren.API;

public class Test01 {
    public static void main(String[] args) {
        MyTime t1 = new MyTime(1970,1,1);
        String s1 = t1.toString();
        //System.out.println(s1); //重写toString之前返回结果 MyTime@1b6d3586
        System.out.println(s1); //重写toString之后返回结果 1970 年 1 月 1 日
        System.out.println(t1);// 默认调用toString()方法      1970 年 1 月 1 日
        System.out.println(t1.toString());// 这里的toString()可以省略    1970 年 1 月 1 日
    }
}
class MyTime{
    int year;
    int month;
    int day;

    public MyTime() {
    }

    public MyTime(int year, int month, int day) {
            this.year = year;
            this.month = month;
            this.day = day;
    }

    @Override
    public String toString() {
        return this.year + " 年 " + this.month + " 月 " + this.day + " 日";
    }
}

toString()方法返回的哈希值往往不是我们所需要的,所以在编写程序时我们要根据自己的需求去重写toString()方法,重写的要求是简洁的、详实的、易阅读的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

守夜人st

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值