Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to create a class with static variable and static method in Java

1 Answer

0 votes
class Item {
    private String itemName;
    private static int counter = 0; 

    public void getItem(String _itemName) {
        itemName = _itemName;
        counter++;
    }

    public void showItem() {
        System.out.println("Item Name: " + itemName + "\tQuantity: " + counter);
    }

    public static int getCounter() {
        return counter;
    }
}

class Program {
    public static void main(String[] s) {
        try {
            Item i1 = new Item();
            i1.getItem("BMW XM Label Red");
            i1.showItem();
            
            Item i2 = new Item();
            i2.getItem("Desktop PC");
            i2.showItem();
            
            Item i3 = new Item();
            i3.getItem("Laptop");
            i3.showItem();

            System.out.println("Total objects created: " + Item.getCounter());
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}


/*
run:

Item Name: BMW XM Label Red	Quantity: 1
Item Name: Desktop PC	Quantity: 2
Item Name: Laptop	Quantity: 3
Total objects created: 3

*/

 



answered Feb 2, 2024 by avibootz

Related questions

1 answer 179 views
2 answers 212 views
1 answer 177 views
1 answer 169 views
1 answer 158 views
...