Generating identifier for new objects

181 Views Asked by At

I'm looking to implement identifier generator for all new objects created and assign value to them. What am I missing in the below code?

public abstract class Figure {

    private static int counter = 0;

    private int number;
   

    public Figure() {
    }

    public static Square createSquare(double a) {
        return new Square(a);
    }
 

    public static int getCounter() {
        return counter;
    }

    public static void setCounter(int counter) {
        Figure.counter = counter;
    }

    public int getNumber() {
        return number = ++Figure.counter;
    }


}
2

There are 2 best solutions below

1
minus On

You should set the number in the static method invocation.

public static Rectangle createRectangle(double a, double b) {
  Figure fg = new Rectangle(a, b);
  fg.number = ++counter;
  return fg;
}

public int getNumber() {
  return number;
}
1
sashkins On

First, remove setCounter method, as it's going to change the private state of the class.

Second, getNumber method should just return this.number. At the moment, whenever the method is called, your number is incremented.

Third, assign the value to the number in the Figure constructor:

this.number = ++counter;

I suppose Square, Circle and Rectangle extend the Figure, so they will call super constructor and will get their number set.

Also, it's better to have a separate class for objects generation, if we are talking about the factory design pattern.