跟踪实例化对象数的Java类变量

时间:2015-02-26 14:20:19

标签: java class

我有这个班,学生,变量StudentID:

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;
  }
}

我希望变量StudentID继续为每个学生分配一个新的ID号。每个ID号应该比创建的最后一个ID号多一个,因此等于已创建的对象总数。现在,每个对象都被分配了ID号1。

3 个答案:

答案 0 :(得分:4)

添加一个静态counter并用它初始化studentID,并在此过程中递增它:

public class Student extends Person{
  static counter = 1;
  int studentID = counter++;
  ...

答案 1 :(得分:1)

您需要一个静态变量来跟踪创建的学生对象的数量。

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;
    }
}

答案 2 :(得分:0)

使studentID成为静态成员

静态成员保存在类的每个实例中,无论有多少个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;
      }
    }