简体   繁体   中英

Why java doesn't allow initializing static variable inside a method?

I know that C++ supports static variables in a method and in java, static members are shared among all objects.but why this code fails to compile in java?

class Learn
{
 static int count = 0;
 Learn(int n)
 {
    count+=n;
 }
 public void method()
 {
    static int count =0;
 }
}
public class th
{
  public static void main(String a[])
  {
    Learn l = new Learn(4);
  }
}

It doesn't allow you to initialize static variables inside methods because variables initialized methods are destroyed after the method has been called, and a static variable is not only accessible outside the method but outside the class. Those two ideas are conflicting.

Java doesn't allow you to declare a static local variable, such as the count you're declaring in method . If you want to initialize the static class variable, then in method , replace

static int count =0;

with

count = 0;

In java, you declare the static variable outside the method to have the same effect as declaring it static inside the method in C++.

I know that using static outside a method in C++ gives the variable "file scope", but java is different.

If you need a few lines of code to initialize the variable, then use an anonymous static method to initialize it when the class loads

static {
    count = 0;
}

Unlike C++, Java doesn't support static local variables. Because In Java, a static variable is a class variable (for whole class). All methods are declared inside the class, Its not possible to declare member function or any variables outside a class. Even main() method should be inside a class. So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.

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