What you want is the ability to constraint intermediate computation results within the relevant method itself. To achieve this, you can refer to the following code example. Suppose you want to maintain a static variable i
across multiple calls of m()
. Instead of having such a static variable, which is not feasible for Java, you can encapsulate variable i
into a field of a class A
visible only to m()
, create a method f()
, and move all your code for m()
into f()
. You can copy, compile, and run the following code, and see how it works.
public class S {
public void m() {
class A {
int i;
void f() {
System.out.println(i++);
}
}
A a = new A();
a.f();
a.f();
a.f();
}
public static void main(String[] args) {
S s = new S();
s.m();
}
}