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虚拟地址)
}
很多类都重写了 Object 的 toString 方法,如: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方法