Java class variable that tracks number of objects instantiated

前端 未结 3 1714
长情又很酷
长情又很酷 2020-12-21 08:09

I have this class, Student, with the variable StudentID:

public class Student extends Person{
  int studentID = 0;
  int level;

  public Student(){

  }         


        
3条回答
  •  天涯浪人
    2020-12-21 09:10

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

提交回复
热议问题