简体   繁体   中英

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.

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.

Your code has several problems:

  1. A User doesn't have any ID. All you have is a static ID, thus shared by all users
  2. You're incrementing the static ID, and then assigning its previous value to the ID right after.
  3. You're not respecting the Java naming conventions.

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:

class User {

    private static int uid = 0;

    private String name;
    private int id;

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

    // getters
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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