Search⌘ K
AI Features

Solution: Unique ID Generator for Orders

Explore how to generate unique IDs for order objects in Java by using static counters and final instance variables. Understand the role of constructors in initializing these values and how encapsulation provides controlled access through getter methods. This lesson helps you grasp key OOP concepts including class-level variables and object-specific data management.

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());
}
}
...