Java class variable that tracks number of objects

2019-01-28 17:45发布

I have this class, Student, with the variable 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;
  }
}

I want the variable StudentID to keep assign each Student created a new ID number. 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. Right now each object is assigned the ID number of 1.

标签: java class
3条回答
Summer. ? 凉城
2楼-- · 2019-01-28 18:03

Make the studentID a static member

Static members are kept throughout each instance of the class no matter how many instances of the clas there are.

   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;
      }
    }
查看更多
看我几分像从前
3楼-- · 2019-01-28 18:15

Add a static counter and initialize studentID with it, incrementing it in the process :

public class Student extends Person{
  static counter = 1;
  int studentID = counter++;
  ...
查看更多
萌系小妹纸
4楼-- · 2019-01-28 18:17

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;
    }
}
查看更多
登录 后发表回答