简体   繁体   English

使用构造函数创建唯一 ID

[英]Create unique ID with constructor

I want to create objects with a name and a unique ID number that increments with the creation of each user.我想创建具有名称和唯一 ID 号的对象,该 ID 号随着每个用户的创建而增加。

class user {

    static int uid = 0;
    String name;

    public user (String name){
       User.uid = uid++;
       this.name = name;
    }
}

When creating user objects in a main method and printing out their ID they all return 0. I think there is a simply fix to this but can't seem to find it elsewhere online.在 main 方法中创建用户对象并打印出他们的 ID 时,它们都返回 0。我认为有一个简单的解决方法,但似乎无法在网上的其他地方找到它。

Your code has several problems:您的代码有几个问题:

  1. A User doesn't have any ID.用户没有任何 ID。 All you have is a static ID, thus shared by all users您拥有的只是一个静态 ID,因此所有用户都可以共享
  2. You're incrementing the static ID, and then assigning its previous value to the ID right after.您正在增加静态 ID,然后立即将其先前的值分配给 ID。
  3. You're not respecting the Java naming conventions.您不尊重 Java 命名约定。

The code should be代码应该是

class User {

    private static int uid = 0;

    private String name;
    private int id;

    public User(String name) {
       uid++;
       this.id = uid;
       this.name = name;
    }

    // getters
}

or, if you want the IDs to start at 0:或者,如果您希望 ID 从 0 开始:

class User {

    private static int uid = 0;

    private String name;
    private int id;

    public User(String name) {
       this.id = uid++;
       this.name = name;
    }

    // getters
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM