How to use static member variable to count object instances in Java

1 Answer

0 votes
class Counter {
  
    static int counter = 0;
 
    public Counter() {
        counter++;
    }
 
    public int ShowObjectNumber() {
        return counter;
    }
}

  
public class MyClass {
 
    public static void main(String[] args) {
  
        Counter o1 = new Counter();
        System.out.println(o1.ShowObjectNumber());
 
        Counter o2 = new Counter();
        System.out.println(o2.ShowObjectNumber());
        
        Counter o3 = new Counter();
        System.out.println(o2.ShowObjectNumber());
    }
}





  
/*
 
run:
 
1
2
3

*/

 
}
 
/*

run:

1
2

*/

 



answered Oct 14, 2016 by avibootz
edited Nov 14, 2023 by avibootz

Related questions

1 answer 127 views
1 answer 192 views
2 answers 238 views
1 answer 130 views
130 views asked Apr 5, 2019 by avibootz
1 answer 181 views
...