简体   繁体   English

为什么java中的静态方法只接受其方法中的final或非final变量,而不是静态?

[英]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? 为什么java中的静态方法只接受其方法中的final或非final变量,而不是静态?

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. Java语言设计人员可能会考虑这一点,并认为静态本地人添加的实际价值很少,以至于他们不值得包含在语言中。 (Certainly, that's the way I would have voted.) (当然,这就是我投票的方式。)

In Java (in Object Oriented Programming in general), objects carry state. 在Java(一般的面向对象编程)中,对象携带状态。 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. 由于java中的每个函数都必须在一个类中,因此可以通过声明类中的字段来获得相同的效果。 It's the simplest way, and java language designers are very conservative. 这是最简单的方法,而且java语言设计者非常保守。 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. 编辑:我猜哲学函数不是java中的第一类。 They're not supposed to store data. 他们不应该存储数据。 Classes are, and they do. 类是,他们这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM