静态字段即类字段,每个实例共享类字段。类字段属于类,不属于任一个对象,可不依赖对象而存在。
书上用这个例子示范了类字段的用法,但我看不出类字段的使用有什么优点。求答。
ublic class StudentTest2
{
public static void main(String[] args)
{
int i;
for(i = 0; i < 10; i++)
{
Student tom = new Student("Tom" + i );
if(i % 2 == 0)
{
tom.setStudentSex("man");
} else
{
tom.setStudentSex("female");
}
tom.setStudentAddress("America");
tom.setStudentNumber();
System.out.println(tom.toString());
}
}
}
class Student
{
private String strName = "";//学生姓名
private int number = 0;//学号
private String strSex = "";//性别
private String strBirthday = "";//出生年月
private String strSpeciality = "";//专业
private String strAddress = "";//地址
private static int nextNumber = 1;
public Student(String name)
{
strName = name;
}
public String getStudentName()
{
return strName;
}
public int getStudentNumber()
{
return number;
}
public void setStudentNumber()
{
number = nextNumber;
nextNumber++;
}
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 setStudentSpeciality(String speciality)
{
strSpeciality = speciality;
}
public String getStudentAddress()
{
return strAddress;
}
public void setStudentAddress(String address)
{
strAddress = address;
}
public String toString()
{
String information = "学生姓名=" + strName + ", 学号=" + number;
if( !strSex.equals("") )
information += ", 性别=" + strSex;
if( !strBirthday.equals(""))
information += ", 出生年月=" + strBirthday;
if( !strSpeciality.equals("") )
information += ", 专业=" + strSpeciality;
if( !strAddress.equals("") )
information += ", 籍贯=" + strAddress;
return information;
}
}
谢谢。