栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Object类中的toString()方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Object类中的toString()方法

1、源代码长什么样?

    public String toString(){
         return this.getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

    源代码上 toString() 方法的默认实现是:

          类名 @ 对象的内存地址转换为十六进制的形式

2、SUN公司设计 toString() 方法的目的是什么?

     toString() 方法的设计目的是:通过调用这个方法可以将一个“Java对象”转换成“字符串表示形式”

3、SUN 公司开发Java语言的时候,建议所有的子类都去重写 toString() 方法。

      toString() 方法应该是一个简洁的、详实的、易阅读的。

   以下代码加深理解

public class Test3{
    public static void main(String[] args) {
        MyTime t1 = new MyTime(2001,10,24);
        String s1 = t1.toString();
        // System.out.println(s1);
        // 重写toString方法之前输出结果为:exercise.homework.java_test.src.exercise.homework.MyTime@1540e19d
        System.out.println(s1);
        // 重写toString方法之后输出结果为:2001年10月24日
    }
}


class MyTime{
    private int year;
    private int month;
    private int day;

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

    public MyTime() {
    }

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

输出结果为:

         

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/677308.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号