开发者

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

开发者 https://www.devze.com 2023-01-16 01:16 出处:网络
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 :

  • JLS - Local Variable Declaration Statements


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消