Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I find the number of instances of a Class? getClasses()???????

Status
Not open for further replies.

Oxymoron

Technical User
Dec 17, 2000
168
GB
Hi.
say you have made 3 instances of a person from class Person, p1, p2 & p3.
Is there a way of returning through a println, to show how many instances of a class exist???
I've tried a few ways of calling the getClasses method from Class Class, but havn't succeeded. If anyone knows i'd be extremely grateful!
thankyou all
JoE we are all of us living in the gutter.
But some of us are looking at the stars.
 
Hi JoE,

One solution would be to maintan a static count of your class. Static variables exists only once per class, irrespective of the number of instances of that class. The idea is to increment the count each time a class is created and decrement the count at finalization.

class Person {

private static int count = 0;

public Person() {
count++;
}

protected void finalize() {
count--;
super.finalize();
}

public getCount() {
return count;
}
}

HTH
scrat
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top