toString()的作用是什么?
将对象中各个属性值按字符串的方式输出出来。也就是:使用文字描述这个对象里各个变量是什么值 ,这个变量是什么类型的变量等
为什么要重写ToString?
任何类都从Object继承了这个方法,不重写toString()方法的话输出的就是一个内存地址,也就是哈希码值,并不是输出这个类的各个变量的值。
不重写返回的是: getClass().getName() + “@” +Integer.toHexString(hashCode());
即: 类名 + @ +hashCode的值 这三者组合而成
下面我们先看一个不重写toString()的案例:
package test;
public class TestToString2 {
public static void main(String[] args){
Student2 stu=new Student2("李渔",22);
System.out.println(stu);//默认调用了toString()方法
//通过编译会发现,上一句输出的内容和下一句输出的内容是完全一样的
System.out.println(stu.toString());//显示调用toString()方法
}
}
class Student2{
String name;
int age;
public Student2(String name, int age) {
this.name = name;
this.age = age;
}
}
如果不重写toString()方法,编译之后打印内容是这样的:
显示的是toString()方法默认提供的返回值:getClass().getName() + “@” +Integer.toHexString(hashCode());
当然我这个是因为有包的存在,所以在类名前面还有一个包名
下面我们再看一下重写toString()方法之后的案例:
package test;
public class TestToString {
public static void main(String[] args){
Student stu=new Student("李渔",22);
String str= stu.toString();
System.out.println(str);
}
}
class Student{
String name;
int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "姓名" + name + ", 年龄" + age ;
}
}
重写之后编译内容是这样的:
通过两个案例的说明,对重写toString()的原因也清楚明白了。
需要知道的是:
打印一个对象,可以直接System.out.println(stu);
但其实println方法内部会自动调用stu 的 toString() 方法,即System.out.println(stu.toString());
如有帮助,请点赞呐。