简体   繁体   中英

Equivalent of C# “static variable” in Java

In C# I can declare a static var in a class. Eg: to count the create instances of class "foo". Like so

class foo
{
    static int countFoo =0;

    public foo()
    {
        countFoo++;
    }
}

Now - for each foo created I can use a getFooCount method to know how many instances were created. How do you do that in Java? I tried to do the same and it doesn't work. Please explain why and how. Thanks!

No, you can do exactly the same and it will work. Sample code:

class Foo
{
    private static int count;

    Foo()
    {
        count++;
    }

    static void printCount()
    {
        System.out.println(count);
    }
}

public class Test
{
    public static void main(String[] args)
    {
        Foo.printCount(); // 0
        Foo foo1 = new Foo();
        Foo foo2 = new Foo();
        Foo.printCount(); // 2        
    }
}

(It would have helped if you'd shown what you'd tried...)

The following works in Java (though its not thread safe)

class Foo { 
    static int countFoo =0;

    public Foo() {
        countFoo++;
    }
}

What exactly is the problem you are having?

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