【发布时间】:2020-11-17 02:16:54
【问题描述】:
我是Java编程的初学者,我想重写下面的代码,而是自己设置id号,我希望id号自动设置为$1,2,3,... $ 我知道我必须使用 id 作为静态变量,并且我应该在构造函数中使用 id++ 递增。问题是我不知道如何自动做到这一点。我希望每个学生都有自己的 id,所以当我写例如 robert.getId() 时,它会给我他的 id,但我不希望 id 成为参数,那么我的对象构造将是:
Students robert = new Students("Robert Smith", 8, 3500);
所以我只需要提供姓名、年级和学费以及自动设置的 id 给 robert 对象,我该怎么做?
package schoolManagementSystem;
public class Students
{
//Instance Variables
private int id,grade, tuition;
private String name;
//Constructors
/**
* constructs an object of the class Student
* @param id id of the student
* @param name name of the student
* @param grade grade of the student
* @param tuition tuition the student has to pay
*/
public Students(int id,String name, int grade,int tuition)
{
this.id = id;
this.name = name;
this.grade = grade;
this.tuition = tuition;
}
public int getId()
{
return id;
}
}
【问题讨论】:
-
你写的java连接数据库了吗?
-
@Spectric 一点也不。我不知道我的问题不够清楚。对不起。我想有一个变量id链接到对象,但不一定要把它写成参数,你关注我了吗?
-
@hirarqi 不,那只是一个非常简单的程序。
-
您的代码现在可以了。是什么阻止您自动设置 ID?
-
有人提到了 AtomicInteger here。看看有没有帮助。
标签: java