实体类重写toString方法

1、用途:

  1. toString()方法 一般出现在System.out.println(类名.toString());
  2. toString()是一种自我描述方法 本身返回的是 getClass().getName() + "@" +Integer.toHexString(hashCode());
  3. 也就是 类名 + @ +hashCode的值

代码示例:

package cn.sh.ideal.eml;


import cn.sh.ideal.framework.entity.ObjectEntity;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Eml extends ObjectEntity {

    //发件人
    private String sendName;
    //发件人邮箱
    private String sendAccount;
    //标题
    private String theme;
    //发件时间
    private Date sendTime;
    //eml文件目录
    private String path;

    SimpleDateFormat smp=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public String toString() {
        return "发件人:"+this.sendName+";发件人邮箱:"+this.sendAccount+";标题:"+this.theme+";发件时间:"+smp.format(this.sendTime)+";邮件目录:"+this.path;
    }
}

这样输出结果便会直观显示:

发件人:***;发件人邮箱:s*****[email protected];标题:测试多封带附件邮件;发件时间:2019-03-21 08:55:54;邮件目录:E:\a\测试多封带附件邮件.eml

而不是:

 com.stu.Eml@2542880d  ==> 类名 + “@” +hashCode值

2.为什么要重写toString()方法

在Object类里面定义toString()方法的时候返回的对象的哈希code码,这个hashcode码不能简单明了的表示出对象的属性。所以要重写toString()方法。
当需要将一个对象输出到显示器时,通常要调用他的toString()方法,将对象的内容转换为字符串.java中的所有类默认都有一个toString()方法。
默认情况下 System.out.println(对象名)或者System.out.println(对象名.toString())输出的是此对象的类名和此对象对应内存的首地址如果想自定义输出信息必须重写toString()方法。

注意事项:

1.必须被声明为public

2.返回类型为String

3.方法的名称必须为toString,且无参数

4.方法体中不要使用输出方法System.out.println()

猜你喜欢

转载自blog.csdn.net/supershuyun/article/details/88736168