[英]Java class variable that tracks number of objects instantiated
I have this class, Student, with the variable StudentID: 我有一个带有变量StudentID的班级Student:
public class Student extends Person{
int studentID = 0;
int level;
public Student(){
}
public Student(String fName, String lName, int gLevel){
super(fName, lName);
if(gLevel >= 0 && gLevel <= 12){
level = gLevel;
}
studentID++;
}
public int getLevel(){
return level;
}
public String toString(){
String toReturn;
toReturn = super.toString() + "\n Grade Level: " + level + "\n ID #: " + studentID;
return toReturn;
}
}
I want the variable StudentID to keep assign each Student created a new ID number. 我希望变量StudentID继续分配给每个Student创建的新ID号。 Each ID number should be one more than the last ID number created, and so equal to the total number of objects that have been created. 每个ID号都应比上一个创建的ID号大一个,并且应等于已创建的对象总数。 Right now each object is assigned the ID number of 1. 现在,每个对象的ID号为1。
Add a static counter
and initialize studentID
with it, incrementing it in the process : 添加一个静态counter
并用它初始化studentID
,并在此过程中增加它:
public class Student extends Person{
static counter = 1;
int studentID = counter++;
...
You need a static variable to keep track of the number of students objects created. 您需要一个静态变量来跟踪创建的学生对象的数量。
public class Student extends Person{
/* Number of students objects created */
private static int studentCount = 0;
int studentID = 0;
int level;
public Student(String fName, String lName, int gLevel){
super(fName, lName);
if(gLevel >= 0 && gLevel <= 12){
level = gLevel;
}
studentID = Student.getNextStudentId();
}
private static synchronized int getNextStudentId() {
/* Increment the student count and return the value */
return ++studentCount;
}
}
Make the studentID a static member 将studentID设为静态成员
Static members are kept throughout each instance of the class no matter how many instances of the clas there are. 静态成员将在整个类的每个实例中保留,无论有多少个clas实例。
public class Student extends Person{
static int studentID = 0;
int level;
public Student(){
}
public Student(String fName, String lName, int gLevel){
super(fName, lName);
if(gLevel >= 0 && gLevel <= 12){
level = gLevel;
}
studentID++;
}
public int getLevel(){
return level;
}
public String toString(){
String toReturn;
toReturn = super.toString() + "\n Grade Level: " + level + "\n ID #: " + studentID;
return toReturn;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.