简体   繁体   中英

What is [Android] Java's equivalent of VB.NET's Static Keyword?

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
    }
}

它是Java中的静态关键字

public static String mVar = "Some Value";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM