Spring boot cors issue

These are short tutorials on how to count the number of instances/objects of a class in java.

An object of a class is created using a new keyword in java. an object is an instance of a class.

A class can have multiple objects.

How do you count the number of objects/instances of a class in java?

Static is the global scope that can be created and accessed by all objects of a class. So static member variables are used to know the count.

Here is a step-by-step guide to counting.

  • In a class, created a static variable(objectCount), and all object has access to it, It contains class scope variables
  • objectCount is initialized with zero initially
  • Static variables are only accessed by static members directly
  • Instance block is defined and incremented its value by one whenever a new object is created.
  • objectCount decremented in finalize method, which calls whenever an object is ready for garbage collection. It is useful to count non-garbage collected objects.
  • Finally, printed the static member variable using a class

Here is an example using instance block


public class Main
{
    private static int objectCount = 0;

    {
        objectCount += 1;
    }
    public static void main(String[] args) {
        Main t1 = new Main();
        Main t2 = new Main();
        System.out.println("Object Count "+getObjectCount());

    }
      public static  int getObjectCount(){
        return objectCount;
    }
     protected void finalize() throws Throwable{
      super.finalize();
        objectCount--;
    }
}

The constructor has a code for incrementing the object count.

Destruction using finalize has a code for decrementing the object count.

The same example can be rewritten with increment objectCount in constructor block

In this, static member variables increment in the constructor, Constructor is called whenever a new object is created.

public class Main
{
    private static int objectCount = 0;

   public MyClass() {
        objectCount++;
    }
    public static void main(String[] args) {
        Main t1 = new Main();
        Main t2 = new Main();
        System.out.println("Object Count "+getObjectCount());

    }
    public static  int getObjectCount(){
        return objectCount;
    }
     protected void finalize() throws Throwable{
      super.finalize();
        objectCount--;
    }
}

The above programs return the following output.

Object Count 2

Conclusion

From above, static member variables are class scope, the instance can be counted in either instance block or constructor approach.

Hope you like this post.