如何在创建对象时在构造函数中自动分配变量

ved*_*ran 1 java

假设我们只有一个带有int ID的简单对象Person来识别它.如何为Person的每个新实例提供新的ID值(+1),但是在该类Person的构造函数中?(我没有使用DB)

Mat*_*eid 9

使用静态AtomicInteger:

final class Foo {
  private static final AtomicInteger seed = new AtomicInteger();
  private final int id;

  public Foo() {
    this.id = seed.incrementAndGet();
  }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见此处:https://stackoverflow.com/a/4818753/17713