跟踪实例化对象数量的Java类变量 [英] Java class variable that tracks number of objects instantiated

查看:148
本文介绍了跟踪实例化对象数量的Java类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级Student,变量StudentID:

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

我希望变量StudentID继续分配创建的每个Student新的ID号。每个ID号都应比上一个创建的ID号大一个,并且应等于已创建的对象总数。现在,每个对象的ID号都分配为1。

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.

推荐答案

使StudentID成为静态成员

Make the studentID a static member

该类的每个实例中都会保留静态成员,无论有多少个clas实例。

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

这篇关于跟踪实例化对象数量的Java类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆