当前位置: 代码迷 >> Java相关 >> 请求解释一下下面的代码
  详细解决方案

请求解释一下下面的代码

热度:165   发布时间:2006-05-15 13:11:00.0
请求解释一下下面的代码
import java.util.ArrayList;
public class ArrayListTest
{
public static void main(String args[])
{
ArrayList list1=new ArrayList();
list1.add(new Student("Tom","20020410"));
list1.add(new Student("Jack","20020411"));
list1.add(new Student("Rose","20020412"));

for(int i=0;i<list1.size();i++)
{
System.out.println((Student)list1.get(i));//注意造型转换
}
}

}
class Student
{
private String strName="";
private String strNumber="";
private String strSex="";
private String strBirthday="";
private String strSpeciality="";
private String strAddress="";

public Student(String name,String num)
{
strName=name;
strNumber=num;
}
public String getStudentName()
{
return strName;
}
public String getStudentNumber()
{
return strNumber;
}
public void setStudentSex(String sex)
{
strSex=sex;
}
public String getStudentSex()
{
return strSex;
}
public String getStudentBirthday()
{
return strBirthday;
}
public void setStudentBirthday(String birthday)
{
strBirthday=birthday;
}
public String getStudentSpeciality()
{
return strSpeciality;
}
public void setStudentAddress(String address)
{
strAddress=address;
}
public String getStudentAddress()
{
return strAddress;
}
public String toString()
{
String information="学生姓名="+strName+",学号="+strNumber;
if(!strSex.equals(""))
information+=",性别="+strSex;
if(!strBirthday.equals(""))
information+=",出生年月="+strBirthday;
if(!strSpeciality.equals(""))
information+=",专业="+strSpeciality;
if(!strAddress.equals(""))
information+=",籍贯="+strAddress;
return information;
}
}
在上面的代码中 输出的结果为什么会自动调用 toString();这个方法`?
还有ArrayList中只能存放对象吗`?
----------------解决方案--------------------------------------------------------
当然会自动调动. 这就要去问SUN为什么要这样设计JAVA了
----------------解决方案--------------------------------------------------------
JAVA和C#长的太像了。
----------------解决方案--------------------------------------------------------
当然像,C#就是从JAVA里面拷贝过来的
----------------解决方案--------------------------------------------------------
都没回答到实质上去``````

里面那个 public String toString()这个方法是我自己定义的吧`?
还是包内里面也有这个方法`
`
----------------解决方案--------------------------------------------------------

Object有这个方法,
你不定义就调用它里面的,你定义了就调用你定义了的
这是最简单的多态


----------------解决方案--------------------------------------------------------
  相关解决方案