java toString()方法的使用
1.未重写toString()方法时
如使用下System.out.println()方法打印一个集合中的Student(自定义类型)类型的元素
Student类
package collection;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//先将重写的toString()注释掉
// @Override
// public String toString() {
// return "Student{" +
// "name='" + name + '\'' +
// ", age=" + age +
// '}';
// }
}
Demo主类
package collection;
import java.util.ArrayList;
import java.util.Collection;
/**
* Collection的使用(2)
* @author qky
*/
public class Demo02 {
public static void main(String[] args) {
Collection collection = new ArrayList();
Student s1 = new Student("张三",12);
Student s2 = new Student("李四",15);
collection.add(s1);
collection.add(s2);
System.out.println(collection);//说明。当使用sout输出时,执行System.out.println() 这个方法默认就会调用一个继承自Object 类型对象的toString方法,所以这里collection后面加不加toString都一样
}

2.重写toString()方法时
如使用下System.out.println()方法打印一个集合中的Student(自定义类型)类型的元素
Student类
package collection;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//将重写的toString()恢复
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Demo主类
package collection;
import java.util.ArrayList;
import java.util.Collection;
/**
* Collection的使用(2)
* @author qky
*/
public class Demo02 {
public static void main(String[] args) {
Collection collection = new ArrayList();
Student s1 = new Student("张三",12);
Student s2 = new Student("李四",15);
collection.add(s1);
collection.add(s2);
System.out.println(collection);//说明。当使用sout输出时,执行System.out.println() 这个方法默认就会调用一个继承自Object 类型对象的toString方法,所以这里collection后面加不加toString都一样
}


浙公网安备 33010602011771号