下面这段代码中public String toString()方法在哪里调用啊?整个程序的运行结构看不太明白,请指点一下.

warmersen 2012-06-08 06:24:04
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));

}

}
...全文
91 1 打赏 收藏 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
淡定的峰哥 2012-06-08
  • 打赏
  • 举报
回复
在这句话上
System.out.println(list.get(i));
会调用到list.get(i).toString()方法
因为list中存放的是Student类型
也就是说会调用Student的toString方法
如果Student类不去覆盖toString()方法就会调用它的超类即Object类的toString方法

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧