Reputation: 963
I have a couple of classes, one of which needs to count how many times object has been created (int fields called lastId). In c++ we had to initialize static fields value in main class and then we were able to correctly use that static field in other classes and count how many objects have been created. What about java? Where do I have to initialize static fields value. Also, I know how to count if object has been created, but what about if object has been deleted? There are no destructors in java, so how can this job be done?
Upvotes: 0
Views: 719
Reputation: 438
How to initialize a static field? 1. Initialize the field while declaring. 2. Initialize in a static block. 3. Initialize to null and set from some other location. This is not really initializing to a value just setting a meaningful value later.
Refer to Dave Doknjas answer for examples.
How to count objects? See Peter Lawrey's answer.
What about Destructors? Since object collection is handled for you, when there is no references left to an object, destructors are not really needed. You should not be trying to manage the collection your self in Java it does an excellent job for you. If you absolutely need something done when the object is being collected you should look into the finalize method, it is run when the object is being collected.
See http://javarevisited.blogspot.com/2012/03/finalize-method-in-java-tutorial.html for more information on finalize.
Upvotes: 0
Reputation: 533442
If all you want to do is count the number of active objects of a type call
jps -lvm # to find the pid of your process
jmap -histo {pid} # count all objects in the system
or
jmap -histo:live {pid} # count objects referenced
This will give you a count of the number of instances, by class.
If you wnt to visualise what you application is doing try
jvisualvm
This will give stats like memory used, threads etc as well a break down of here CPU is being consumed and which objects are created.
What about java?
You just initialise them with something like
static int counter = 0;
Where do I have to initialize static fields value.
The same place you would initialise any other field.
BTW if you did just this
static int counter;
It would be 0 by default anyway, so I suspect you don't need to initialise it.
what about if object has been deleted?
That's easy because you can't delete objects. So the answer is always 0. ;)
There are no destructors in java, so how can this job be done?
Java doesn't have such a thing so the question is kind of meaningless.
Upvotes: 2
Reputation: 6542
You can initialize either in the declaration or in the static initializer:
public class test
{
//this is fine:
public static int i = 1;
//or this:
public static int i;
static
{
i = 1;
}
}
Upvotes: 1