java的toString方法

toString方法

toString() 方法在 Object 类中定义,其返回值是 String 类型,返回类名和他的引用地址。
在进行String与其他类型数据的连接时,自动调用 toString() 方法

Date now = new Date();
System.out.println("now="+now);//相当于
System.out.println("now="+now.toString());

now=Mon Oct 18 07:59:28 CST 2021
now=Mon Oct 18 07:59:28 CST 2021

可以根据需要在用户自定义类型中重写 toString() 方法
如String类重写了 toString() 方法,返回字符串的值。

s1 = "hello"
System.out.println(s1); //相当于System.out.println(s1.toString);

基本类型数据转换为 String 类型时,调用了对应的包装类 toString() 方法

int a = 10;
System.out.println("a="+a);//a=10

当我们输出一个对象的引用时,实际上相当于调用了当前对象的 toString 方法。

public class toString {
    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student.toString());//Demo05.Student@1b6d3586
        System.out.println(student);//Demo05.Student@1b6d3586
    }
}
//Object类中toString()的定义
public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
        //类名@对空间中的哈希码(jvm虚拟地址)
    }

很多类都重写了 ObjecttoString 方法,如:String、Date、File类、包装类等。
使得在调用对象的 toString() 时,返回实体内容。

public class toString {
    public static void main(String[] args) {
        String str = new String("java");
        System.out.println(str);//java

        Date now = new Date();
        System.out.println(now);//Mon Oct 18 08:16:37 CST 2021
    }
}

自定义类也可以重写 toString() 方法,调用此方法时,返回对象的实体内容。

//新建java对象Student,重写toString()方法
public class Student {
    String name = "XiaoMing";
    int number = 123456;
    //手动实现
    @Override
    public String toString() {
        return "Student[name = "+this.name+"number"+this.number+"]";
    }
}
//调用Student的toString()方法
public class toString {
    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student);//Student[name = XiaoMingnumber123456]
    }
}

需要时重写toString方法

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值