本帖最后由 Shimano 于 2014-5-24 09:42 编辑
- import java.util.*;
- class Person
- {
- private String name;
- private int age;
- Person(String name, int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public String toString()
- {
- return name+"..."+age;
- }
- }
- class Question
- {
- public static void main(String[] args)
- {
- ArrayList al = new ArrayList();
-
- al.add(new Person("lisi1",31));
- al.add(new Person("lisi2",32));
- al.add(new Person("lisi3",33));
- al.add(new Person("lisi4",34));
-
-
- sop(al.toString());//al调用的怎么是Person类中重写toString方法?
-
- Iterator it = al.iterator();
-
- while(it.hasNext())
- {
-
- Object obj = it.next();
- Person p = (Person)obj;
-
- sop(p.toString()+"....");
- //sop(p.getName()+"..."+p.getAge());
- }
-
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 /*打印结果:
[lisi1...31, lisi2...32, lisi3...33, lisi4...34]
lisi1...31....
lisi2...32....
lisi3...33....
lisi4...34....
*/
我在Person类中重写Object类的toString方法,在迭代过程中向下转型,
p调用toString方法打印出name和age。
我在迭代之前,用al调用toString方法,依照打印结果来看,
al也是调用的Person类中的toString方法,这是为什么?
al应该调用ArrayList继承Object类中的toString方法才对吧!求解释.......
|