Reputation: 3748
Why should a static method in java accept only final or non final variables within its method, but not static?
For example I have the following method:
public static void myfunc(int somethig)
{
int a=10;
final int b=20;
static int c=30; //gives Error why?
}
Upvotes: 3
Views: 846
Reputation: 11250
In Java (in Object Oriented Programming in general), objects carry state. Methods should share state through objects attributes, not through static local variables.
Upvotes: 3
Reputation: 5676
Since every function in java has to be inside a class, you can get the same effect by declaring fields in your class. It's the simplest way, and java language designers are very conservative. They'd never add a feature like that, when there's a more obvious and less complex way to do the same thing.
EDIT: I guess philosophically functions aren't first class in java. They're not supposed to store data. Classes are, and they do.
Upvotes: -1
Reputation: 719307
The question is: why not?
Consider this: what would a static local variable mean?
I suggest that the only sensible meaning would be that this:
public class Foo {
static int bar = 21;
public void foo() {
static int bar = 42; // static local
return bar;
}
}
is equivalent to this:
public class Foo {
static int bar = 21;
private static foo$bar = 42; // equivalent to static local
public void foo() {
return bar;
}
}
In other words, (hypothetical) static locals would be equivalent to regular static attributes with slightly different visibility rules.
The Java language designers probably considered this, and decided that static locals added so little of real value that they were not worth including in the language. (Certainly, that's the way I would have voted.)
Upvotes: 11
Reputation: 3147
You can not have a static variable. There is no such thing. You can have a class variable as static instead.
Upvotes: 1
Reputation: 93187
You can't have static local variable. It doesn't really make sense.
However you can have a static field in your class.
Resources :
Upvotes: 2