关于Objetct类中的toString()方法简单描述

toString()

/*
    关于Object类中的toString()方法:
        1、源码长什么样子?
        public String toString(){
            return this.getClass().getName() + "@" + Interger.toHexString(hashCode());
        }
        源码上toString()方法的默认实现是:
            类名@对象的内存地址转换为十六进制的形式

        2、SUN公司设计toString()方法的目的是什么?
            toString()方法的作用是什么?
                toString()方法的设计目的是:通过调用这个方法可以将一个"java对象"转换成"字符串表示形式"。

         3、其实SUN公司开发java语言的时候,建议所有的子类都去重写toString()方法。
            toString()方法应该是一个简洁的,详实的,易阅读的。
 */

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

//测试类程序
public class Object_toStringTest {
    public static void main(String[] args) {
        MyTime t1 = new MyTime(1970,1,1);
        //一个日期对象转换成字符串形式的话,我们希望看到具体的日期信息。
        String s1 = t1.toString();//一个引用toString()方法,所有指向对象的内存地址的哈希值转换成十六进制数
        System.out.println(t1);
        //MyTime类重写toString()方法之前
        System.out.println(s1);//MyTime@28d93b30

        //重写toString()方法之后
        System.out.println(s1);

        //输出引用的时候会自动调用toString()方法
        System.out.println(t1);
    }

}


//我的时间
class MyTime{
    int year;
    int mouth;
    int day;

    public MyTime(){

    }

    public MyTime(int year, int mouth, int day) {
        this.year = year;
        this.mouth = mouth;
        this.day = day;
    }
    //重写toString()方法
    //这个toString()方法怎么重写?
    //越简洁越好,可读性越强越好。
    //向简洁的、详实的、易阅读的方向发展
    public String toString(){
        return this.year+"年"+this.mouth+"月"+this.day+"日";
    }

/*
    哈希值概述
    是Jdk根据对象的地址/String/数字算出来一串数字(int)
 */
  //不重写toString()方法,会输出哈希值转换成十六进制
  /*
   public String toString(){
        return this.year+"/"+this.mouth+"/"+this.day;
    }
    */

}

**对hashCode简单的描述

/**
 *      hashCode方法:
 *          在Object中的hashCode方法是怎样的?
 *              public native int hashCode();
 *
 *              这个方法不是抽象方法,带有native关键字,底层调C++程序。
 *
 *          hashCode()方法返回的是哈希码:
 *              实际上就是一个java对象的内存地址,经过哈希算法,得出一个值。
 *              所以hashCode()方法的执行结果可以等同看做一个java对象的内存地址。
 */

public class Object_hashCode {
    public static void main(String[] args) {
        Object o = new Object();
        int hashCodeValue1 = o.hashCode();

        //对象内存地址经过哈希算法可以转换的一个数字,可以等同看做内存地址。
        System.out.println(hashCodeValue1);   //685325104

        A a = new A();
        int hashCodeValue2 = a.hashCode();
        System.out.println(hashCodeValue2); //460141958

    }
}

class A {

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

你困了吗?

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

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

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

打赏作者

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

抵扣说明:

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

余额充值