简体   繁体   中英

Why should a static method in java accept only final or non final variables within its method, but not static?

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

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.)

In Java (in Object Oriented Programming in general), objects carry state. Methods should share state through objects attributes, not through static local variables.

You can't have static local variable. It doesn't really make sense.

However you can have a static field in your class.


Resources :

You can not have a static variable. There is no such thing. You can have a class variable as static instead.

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.

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