Is there a Java equivalent - specifically on Android - for VB.NET's Static
keyword? For those not familiar with VB.NET, take the following code snippet...
Sub MyFunc()
Static myvar As Integer = 0
myvar += 1
End Sub
The Static
keyword makes it so myvar retains its value between subsequent calls to MyFunc.
So after each of three calls to MyFunc, myvar's value would be: 1
, 2
and 3
.
How do you make a cross-call persistent variable within a method in Java? Can you?
No. Within a method, Java doesn't have something which can be remembered across various calls.
if you want to persist a value across multiple calls of a method, you should store it as instance variable or class variable.
Instance variables are different for each object/instance while class variables (or static variables) are same for all the objects of it's class.
for example:
class ABC
{
int instance_var; // instance variable
static int static_var; // class variable
}
class ABC_Invoker
{
public static void main(string[] args)
{
ABC obj1 = new ABC();
ABC obj2 = new ABC();
obj1.instance_var = 10;
obj2.instance_var = 20;
ABC.static_var = 50; // See, you access static member by it's class name
System.out.prinln(obj1.instance_var);
System.out.prinln(obj2.instance_var);
System.out.prinln(ABC.static_var);
System.out.prinln(obj1.static_var); // Wrong way, but try it
System.out.prinln(obj2.static_var); // Wrong way, but try it
}
}