How can I tell if a method is being called so that I can add a counter to measure the total calls of this method?
Edit for clarification.
assuming that I have
class anything{
public String toString() {
++counter;
return "the time this method is being called is number " +counter;
}
}//end class
and I am creating an instance of anything in a main method 3 times,
and the output I want if I call its toString() the whole 3 times is this:
- the time this method is being called is number 1
- the time this method is being called is number 2
- the time this method is being called is number 3
I want the counter being added succesfully inside the class and inside the ToString() method and not in main.
Thanks in advance.
You can use a private instance variable counter, that you can increment on every call to your method: –
Update : –
According to your edit, you would need a static variable, which is shared among instances. So, once you change that varaible, it would be changed for all instances. It is basically bound to class rather than any instance.
So, your code should look like this: –