I want to implement a method which has a different behavior when called for the first time, and then when it is called for the second time.
How to do that?
Instance methods in Java have access to the state of the class. Add a variable to indicate whether or not the methods has been called before, and use it to decide between two paths to take inside the method:
class FirstTimeCaller {
private boolean isFirstTime = true;
void methodWithState() {
if (isFirstTime) {
... // Do first-time thing
isFirstTime = false;
} else {
... // Do the other thing
}
}
}
This works for instance methods of the same object: first-time call will be executed the first time you call methodWithState
on each new object of FirstTimeCaller
class.
If you wish to implement the same behavior for a static method, or you'd like to have the first invocation on any instance to do a different thing, and all subsequent calls to do something else, make isFirstTime
field static
.
You can simply create a variable
int counter = 0; // This means the method has not been called yet
And when the method is called then just do this code in it:
counter++; // Increment by 1 for each new call
And you have a number of method calls stored in a variable "counter" so you can choose what to do with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With