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.
// 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();
}
}
Item ID: 1, Item Name: Laptop
Item ID: 2, Item Name: Smartphone
Item ID: 3, Item Name: Tablet
Total Items Created: 3
Item
itemCount
, shared across all objects.itemCount
each time a new Item
is created.itemName
and itemID
private.displayItem()
prints individual item details.displayTotalItems()
(static method) prints the total number of items created.ItemCounterExample
(Main Class)
Item
objects.displayItem()
to show each item’s details.displayTotalItems()
to show the total count of items created.✅ Shared Across Objects – Tracks the count of all objects created.
✅ Automatic Numbering – Provides unique incremental IDs.
✅ Efficient & Organized – Prevents manual tracking of object count.