toString()
方法返回对象的字符串表示形式。如果打印任何对象,java 编译器会在内部调用该对象的 toString()
方法。 因此,重写 toString()
方法,返回所需的输出,它可以是对象的状态等,具体取决于实现。 通过重写 Object
类的 toString()
方法,可以返回对象的值,所以不需要写太多代码。考虑以下示例:
class Student {
int rollno;
String name;
String city;
Student(int rollno, String name, String city) {
this.rollno = rollno;
this.name = name;
this.city = city;
}
public String toString() {//overriding the toString() method
return rollno + " " + name + " " + city;
}
public static void main(String args[]) {
Student s1 = new Student(10101, "张三", "海口");
Student s2 = new Student(10102, "李帅", "广州");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
运行结果如下:
10101 张三 海口
10102 李帅 广州