创建简单的学生班 [英] Creating simple Student class

查看:73
本文介绍了创建简单的学生班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java创建一个类,它是了解对象,方法等的基本类。无论如何,类名是Student,并且应该为每个新创建的对象分配一个学生ID。学生ID的起始编号为1000000,然后递增1,因此每个新对象都应为该类分配一个学生编号,即10000001、100000002等。

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

但是,当我创建此类的对象时,学生证会不断为每个人提供相同的学生人数10000000。请帮助

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

推荐答案

您的 getStudentID 函数将返回静态计数器,而不是实例变量。

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

public long getStudentID() {
    return nextID;
}

应为:

public long getStudentID() {
    return studentID;
}

此外,在构造函数中,您定义一个名为 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;

您正在为参数分配一个值,然后在方法结束时将其丢弃。您应该删除该参数,因为您正在跟踪类中的ID,因此无需传递该参数。您也可以将其更改为 this.studentID : code>此明确引用实例字段。

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.

这篇关于创建简单的学生班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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