mardi 11 février 2020

Make code execute each time an object is created when there are several constructors in a class

I have a class User that I want to assign an id to on creation. I do this to do so:

public class User  {
  private String firstName;
  private String lastName;

  private int id;
  private static int count;

  {
    id = count++;
  }

  public User()  {}

  public User(String firstName)  {...}

  public User(String lastName)  {...}
}

However I'm not sure if it's the best approach? Would a better practice be putting the id = count++ code inside the default constructor and calling it in every other constroctor like:

public User(String firstName)  {
  this();
  ...
}

class User also has children like Student, Worker, etc.

Aucun commentaire:

Enregistrer un commentaire