How to count the number of instances of a particular class in inheritance tree, created explicitly?

12,378
public class Foo {
    private static int fooCount = 0;

    public Foo() {
        if (this.getClass() == Foo.class) {
            fooCount++;
        }
    }

    public static int getFooCount() {
        return fooCount;
    }
}
Share:
12,378
sudhir
Author by

sudhir

Updated on June 04, 2022

Comments

  • sudhir
    sudhir about 2 years
    class A { 
        static int i;
        {
            System.out.println("A init block"+ ++i);
        }
    
    }
    class B extends A {
        static int j;
        {
            System.out.println("B init block"+ ++j);
        }
    }
    class C extends B {
        static int k;
        {
            System.out.println("C init block"+ ++k);
        }
            public static void main(String abc[])
            {
              C c =new C();
            }
    }
    

    In the code above, we can easily count the number of objects created for each class. But if i want to check the number of object created explicitly , i mean if I create C's object using new C(), or B's object using new B(), then it should give the count accordingly

    Take for example,

    C c2=new C();
    B b2=new B();
    

    So it should give the output of B's count as 1 and not 2.

  • Rajdeep Siddhapura
    Rajdeep Siddhapura over 9 years
    what is the need of checking this.getClass() == Foo.class ?
  • JB Nizet
    JB Nizet over 9 years
    If you don't fooCount will be incremented when a subclass of Foo is instantiated, since the subclass constructor always calls the superclass constructor.
  • weno
    weno almost 5 years
    I believe this produces negative values for Test Count if number of NewTest instances is larger than number of Test instances.