Search⌘ K
AI Features

Solution: Unique ID Generator for Orders

Explore how to implement a unique ID generator for order objects by using static variables as global counters and final instance variables for immutable IDs. Understand how constructors manage the incrementation of the order count and the assignment of unique identifiers, ensuring each order instance has a distinct ID.

We'll cover the following...
Java 25
public class Order {
// Static field acting as a shared global counter for all orders
private static int totalOrders = 0;
// Final instance field ensuring the ID is unique and immutable per object
private final String orderID;
// Constructor
public Order() {
totalOrders++; // Increment the shared counter first (e.g., 0 -> 1, 1 -> 2)
this.orderID = "ORD-" + totalOrders; // Assign the current count to this specific order's ID
}
// Getter method to retrieve the ID
public String getOrderID() {
return orderID;
}
public static void main(String[] args) {
Order o1 = new Order();
Order o2 = new Order();
Order o3 = new Order();
System.out.println(o1.getOrderID());
System.out.println(o2.getOrderID());
System.out.println(o3.getOrderID());
}
}
...