Unique ID for Java classes

Posted on August 5, 2010
by

As I was writing some Java code for my finale dissertation, I wanted to give my objects an unique ID in order to distinguish them easily. I thus wrote the following abstract class that does the job well for me:


package motd.utils;
 
/**
* Makes a class identifiable with an unique ID for its objects
*
* @author Cyril Mazur cyrilmazur.com
*/
abstract public class Identifiable {
 
  /**
  * The object's ID
  */
  protected int id;
 
  /**
  * Constructor
  */
  public Identifiable() {
    this.id = getNextId();
  }
 
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // GETTERS AND SETTERS
 
  public int getId() {
    return id;
  }
 
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // STATIC
 
  /**
  * Index for the object's ID
  */
  protected static int index = 0;
 
  /**
  * Return next ID
  * @return int
  */
  protected static int getNextId() {
    return ++index;
  }
}

Download Identifiable.java here

Make your class to extend Identifiable, don’t forget to call the super() constructor, and you’re done.

Now, all of your objects will have an ID attribute which will identify them in a unique way. Of course this attribute is private, and I’ve added a getter for it, since it’s a good OOP practice.

Note 1: with my class, the counter is global. It means that when the counter increments, it increments for all the classes that extend Identifiable in your program. Two objects of different classes will never have the same ID. I don’t know if it’s wrong or if it’s right in the end… If someone has an idea on how to make the counter dedicated to each class, feel free to leave a comment 🙂

Note 2: I’m far from being a god of Java, and it’s likely that my tip is just for beginners who don’t use frameworks that would already encapsulate this feature

About the author

Cyril Mazur is a serial web entrepreneur with experience in various fields: online dating, forex & finance, blogging, online advertising... who enjoys building things that people like to use.

Leave the first comment