class Foo {
public Foo() { }
}
class Bar {
static Foo foo = new Foo(); // This is legal...
public static void main(String[] args) {
static int a = 0; // ... But why this is not?
}
}
Why can't we declare a static variable inside of a static function?
we can't declare Static variable inside the method or constructor. Because static variables are class level variables. Most of the programmer says "YES". But we can't declare Static variable inside the method or constructor.
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.
You have to make the static final static
or remove static
.
In Java, static means that it's a variable/method of a class, it belongs to the whole class but not to one of its certain objects. This means that static keyword can be used only in a 'class scope'.
Generally, in C, you can have statically allocated locally scoped variables. Unfortunately this is not directly supported in Java. But you can achieve the same effect by using nested classes.
For example, the following is allowed but it is bad engineering, because the scope of x is much larger than it needs to be. Also there is a non-obvious dependency between two members (x and getNextValue).
static int x = 42;
public static int getNextValue() {
return ++x;
}
One would really like to do the following, but it is not legal:
public static int getNextValue() {
static int x = 42; // not legal :-(
return ++x;
}
However you could do this instead,
public static class getNext {
static int x = 42;
public static int value() {
return ++x;
}
}
It is better engineering at the expense of some ugliness.
Other people have explained how to deal with this at the coding level. Allow me to explain the logical and philosophical reasons why static within a method makes no sense. You have to ask the question "How long do you want the variable to last?".
So how long do you want your 'static within a method' variable to last? If it's until the end of the method, then you can just use it without static. If it's for the lifetime of the class, then you can declare it as a static member variable. What other options are there?
C++ allows statics within a method, but they end up behaving just like a static class variable, but with reduced scope. Even in C++ they are rarely used. They also end up being stored exactly like static member variables. The pattern is widely considered to be dangerous and confusing, because it mounts to having a method 'remember' the value of what looks like a local variable from one invocation to another - a value which would be changed if some other piece of code chooses to execute the method in between the two invocations.
The Java designers decided that the small amount of benefit wasn't worth the additional complexity of the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With