Creating simple Student class

别等时光非礼了梦想. 提交于 2020-04-30 07:54:15

问题


I'm creating a class using java and it's a basic class to understand objects,methods etc.. anyways the class name is Student and it is supposed to assign a student ID to each newly created object. Student ID's start at 1000000 and increment by 1, so every new object should have the class assign a student ID, 10000001, 100000002 etc..

public class Student {

 private static long nextID=10000000;
 private long studentID;
 //etc..

 public Student (String name, long studentID, int count, double total score) {
        totalScore=0;
        count=0;
        this.name=name;
        studentID=nextID;
        nextID++;

 }

 public long getStudentID() {
       return nextID;`
 }

however when I create objects of this class the student ID keeps giving everyone the same student number, 10000000. please help


回答1:


Your getStudentID function is returning the static counter instead of the instance variable.

public long getStudentID() {
    return nextID;
}

Should be:

public long getStudentID() {
    return studentID;
}

Also, in the constructor, you define a parameter called studentID, which hides the instance field of the same name, so when you do this:

studentID=nextID;

You are assigning a value to the parameter, which is then discarded when the method ends. You should remove the parameter, since you are tracking ID inside the class, you don't need to pass it in. You could also change it to this.studentID: the this explicitly refers to the instance field.




回答2:


Your getStudentID method is returning the wrong value. It should return the studentID field, not the static nextID field.

Like so:

public long getStudentID(){
    return this.studentID;
}



回答3:


use this: this.studentID=nextID; instead of studentID=nextID;



来源:https://stackoverflow.com/questions/18972485/creating-simple-student-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!