下面这段代码中public String toString()方法在哪里调用啊?整个程序的运行结构看不太明白,请指点一下.
import java.util.*;
class Student {
private String name;
private String phone;
public Student(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String toString() {
return name + ":" + phone;
}
}
public class Test4 {
public static void main(String[] args) {
Student st1 = new Student("John", "23214");
Student st2 = new Student("Alice", "4563");
List<Student> list = new ArrayList<Student>();
list.add(st1);
list.add(st2);
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
}
}
------解决方案--------------------
在这句话上
System.out.println(list.get(i));
会调用到list.get(i).toString()方法
因为list中存放的是Student类型
也就是说会调用Student的toString方法
如果Student类不去覆盖toString()方法就会调用它的超类即Object类的toString方法