In C, you can have statically allocated locally restricted variables. Unfortunately, this is not directly supported in Java. But you can achieve the same effect using nested classes.
For example, the following is allowed, but this is bad engineering, since the scope of x is much larger than it should be. There is also an unobvious dependency between the two members (x and getNextValue).
static int x = 42; public static int getNextValue() { return ++x; }
I would like to do the following, but this is not legal:
public static int getNextValue() { static int x = 42;
However, you could do it,
public static class getNext { static int x = 42; public static int value() { return ++x; } }
This is better engineering due to some ugliness.
John heckel
source share