我是java编程的初学者,我想重写下面的代码,但是为了自己设置id号,我希望id号自动设置为$1,2,3,…$我知道我必须使用id作为静态变量,我应该在构造函数中用id++递增。问题是我不知道如何自动生成。我希望每个学生都有自己的id,因此当我编写例如robert.getid()时,它会给我他的id,但我不希望id是一个参数,那么我的对象构造将是:
Students robert = new Students("Robert Smith", 8, 3500);
所以我只需要提供姓名、年级和学费,id自动设置为robert object,我怎么做?
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;
}
}
2条答案
按热度按时间bq8i3lrv1#
这应该管用。让我知道
s4n0splo2#
使用atomicinteger和getandincrement()方法,您的程序将如下所示