Java Code Example: Create Items with Counter

In many real-world applications, such as inventory systems, product management, or ticketing, we need to track the number of objects created dynamically. This is where a static counter in Java comes in handy.

Static Variables – Shared across all objects to keep a global count.
Constructors – Automatically increment the counter when a new object is created.
Encapsulation – Keeps data private and provides controlled access.

This example demonstrates how to count the number of items created using a static counter variable.


Java Code Example:

// Class representing an Item
class Item {
    private static int itemCount = 0; // Static counter shared across all objects
    private String itemName;
    private int itemID;

    // Constructor to initialize the item and update counter
    public Item(String name) {
        this.itemName = name;
        this.itemID = ++itemCount; // Increment counter and assign ID
    }

    // Method to display item details
    public void displayItem() {
        System.out.println("Item ID: " + itemID + ", Item Name: " + itemName);
    }

    // Static method to get total items created
    public static void displayTotalItems() {
        System.out.println("Total Items Created: " + itemCount);
    }
}

// Main class
public class ItemCounterExample {
    public static void main(String[] args) {
        // Creating Item objects
        Item item1 = new Item("Laptop");
        Item item2 = new Item("Smartphone");
        Item item3 = new Item("Tablet");

        // Displaying item details
        item1.displayItem();
        item2.displayItem();
        item3.displayItem();

        // Displaying total number of items created
        Item.displayTotalItems();
    }
}

Expected Output:

Item ID: 1, Item Name: Laptop
Item ID: 2, Item Name: Smartphone
Item ID: 3, Item Name: Tablet
Total Items Created: 3

Code Explanation:

  1. Class Item
    • Defines a static counter itemCount, shared across all objects.
    • The constructor increments itemCount each time a new Item is created.
    • Encapsulation: Keeps itemName and itemID private.
    • displayItem() prints individual item details.
    • displayTotalItems() (static method) prints the total number of items created.
  2. Class ItemCounterExample (Main Class)
    • Creates three Item objects.
    • Calls displayItem() to show each item’s details.
    • Calls displayTotalItems() to show the total count of items created.

Why Use a Static Counter?

Shared Across Objects – Tracks the count of all objects created.
Automatic Numbering – Provides unique incremental IDs.
Efficient & Organized – Prevents manual tracking of object count.