0

I have a class of Orders and it has the number of the order, and it has to increase by 1 every time a new order is created.

I tried to use static but it changed the number of all the orders

Any help?

tonga
  • 191
  • 3
  • 12
  • Do you need something like ID generator? – Vasily Liaskovsky Nov 11 '21 at 23:06
  • 1
    You need two fields - a `static` one that stores the number of objects you've created, and a non-static one that stores the id of each object. The constructor assigns the value of the `static` field to the non-static one. You also need to think about whether your program will be multi-threaded, because the thread-safe version of this is slightly more complicated. – Dawood ibn Kareem Nov 11 '21 at 23:08

2 Answers2

3

If it is ID generator you need, there is simple solution with combination of static + instance variable

public class Order {
  private static volatile long nextId = 0L;
  private long id;

  public Order (){
    id = nextId++;
  }
}

EDIT

I'll just leave it here for reference Is a volatile int in Java thread-safe?

Vasily Liaskovsky
  • 2,248
  • 1
  • 17
  • 32
  • 3
    This is not thread-safe. An increment of a `volatile` variable is two separate memory operations. That's not atomic. You either need to use a mutex, or an `AtomicInteger`. – Stephen C Nov 11 '21 at 23:14
  • @StephenC assuming thread safety is a requirement, of course. But since this is the second time today that this question has been asked, it's more likely a classroom exercise, for a class that haven't yet learnt about threads. – Dawood ibn Kareem Nov 11 '21 at 23:29
  • 1
    That is true. We don't know if thread-safety is a requirement. But if it isn't then the `volatile` is not necessary. In short, in this context `volatile` is EITHER unnecessary OR insufficient. – Stephen C Nov 12 '21 at 00:32
  • @StephenC you are absolutely right (as you so often are). – Dawood ibn Kareem Nov 12 '21 at 01:07
  • It is my goal to be often right :-) – Stephen C Nov 12 '21 at 01:14
0

maybe like that?

public class Order {
  private long id;

  public Order (long lastId){
    id = lastId++;
  }
}

so, when you create a new you do Order order = new Order(otherOrder);

  • This is wrong. Where is the caller of the constructor going to get the correct parameter value from? And note that the `lastId++` only changes the local variable. The value of `otherOrder` does not change. Java method parameters are call-by-value!! – Stephen C Nov 12 '21 at 01:16