如何在 Java 中创建静态局部变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2079830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:19:45  来源:igfitidea点击:

How do I create a static local variable in Java?

javascopestatic

提问by gameover

I've read Java does not support staticlocal variables unlike C/C++. Now if I want to code a function with a local variable, whose value should persist between function calls, how do I do that?
Should I resort to using instance variables?

我读过 Java 不支持static与 C/C++ 不同的局部变量。现在,如果我想用一个局部变量编写一个函数,它的值应该在函数调用之间保持不变,我该怎么做?
我应该求助于使用实例变量吗?

采纳答案by Ellie P.

You can have a static class variable, which will be preserved across all instances of the class. If that's what you want. If not, use an instance variable, which will only be preserved across method calls on this object.

您可以拥有一个静态类变量,它将在类的所有实例中保留。如果那是你想要的。如果没有,请使用实例变量,该变量只会在此对象上的方法调用之间保留。

public class Foo {
   static int bar;
   //set bar somewhere

   public int baz() {
      return 3 * bar;
   }
} 

回答by Chii

Should I resort to using instance variables?

我应该求助于使用实例变量吗?

yes - after all, that is what instance variables are for. They store the state between invocations of the methods of the object. Having static class variables can sort of achieve the same result, but can make your program more coupled and harder to test/mock/maintain.

是的 - 毕竟,这就是实例变量的用途。它们存储对象方法调用之间的状态。拥有静态类变量可以达到相同的结果,但会使您的程序更加耦合并且更难测试/模拟/维护。

回答by paradigmatic

If you want to reuse variable value between function calls and isolate this variable from other methods, you should encapsulate it in an object. First, define a class with only the "static-like" variables and the function you need:

如果要在函数调用之间重用变量值并将此变量与其他方法隔离,则应将其封装在一个对象中。首先,定义一个只有“类静态”变量和你需要的函数的类:

class MyFunctionWithState {
    private int myVar = 0;
    public int call() {
      myVar++;
      return myVar;
    }
 }

Then, from your client code:

然后,从您的客户端代码:

class Foo {
    private MyFunctionWithState func = new MyFunctionWithState();
    public int bar() {
      return func.call();
    }
 }

Now if funcrelies on the internal state of Fooyou can either pass the relevant data through call()or pass an instance of Fooand let the function call the appropriate getters:

现在,如果func依赖于您的内部状态,Foo您可以传递相关数据call()或传递一个实例Foo并让函数调用适当的 getter:

class MyFunctionWithState {
    private int myVar = 0;
    public int call( Foo f ) {
      myVar += f.getBaz();
      return myVar;
    }
 }

class Foo {
    private MyFunctionWithState func = new MyFunctionWithState();
    public int bar() {
      return func.call( this );
    }
    public int getBaz() {  /*...*/  }
 }

回答by user2626445

Local Variables are variables inside a method. Only method gets to access these variables. you cannot have a static local variable , but you can use instance variables or class variables.

局部变量是方法内部的变量。只有方法可以访问这些变量。您不能有静态局部变量,但可以使用实例变量或类变量。

If you have your method as static which by default creates a copy of this method to all the objects and cant be broken down any further as local variables limit their access only to the method in which they reside.

如果您的方法是静态的,默认情况下会为所有对象创建此方法的副本,并且不能进一步分解,因为局部变量将它们的访问权限限制为它们所在的方法。

回答by valery

final int intVar = 1; // Will be inited only once. Behaves as C++ static local var in the method.

最终 int intVar = 1; // 只会被初始化一次。在方法中表现为 C++ 静态局部变量。

回答by Levite

In the following example countbehaves like a static localvariable, that you might use in C:

在以下示例中,count行为类似于静态局部变量,您可以在 C 中使用它:

public class Foo {

   private int count = 0;

   public int getCount() {
       return count++;               
   }
} 

There are no static localvariables like other languages support. Since java is very "class"-oriented, it tries to bring it to that context. If you want to simulate that behavior, you use an instance variable, which is only used by this method. So this is static for different methodcalls, not for the class itself.

没有像其他语言支持的静态局部变量。由于 java 非常面向“类”,因此它试图将其带入该上下文。如果您想模拟该行为,您可以使用一个实例变量,该变量仅由该方法使用。所以这对于不同的方法调用是静态的,而不是类本身。

回答by Alex K

Either you marked an answer correct that wasn't, or you actually wanted static class variables - but the right answer is basically Levit's, or technically a mixture of all the answers.

要么你标记了一个正确的答案,要么你实际上想要静态类变量 - 但正确的答案基本上是 Levit 的,或者技术上所有答案的混合。

For people from a C background like me, truly wanting static function-local variables purely for the scope advantage over globals, it seems the answer is you can't in Java. Not without doing something like @paradigmatic is going for with an instance of a class with a static global and getter() unique to the instance of the class you are running your function in.

对于像我这样有 C 背景的人来说,真正想要静态函数局部变量纯粹是为了比全局变量的范围优势,似乎答案是你不能在 Java 中。不是不做类似@paradigmatic 的事情,就是使用一个类的实例,该类的静态全局和 getter() 是您运行函数的类的实例所独有的。

If, as I suspect, you're running the class as a Singleton, or completely statically like the inately procedural programmer we all started as, @Ellie P's or @user2626445's answer would work fine since no other instance is going to screw up your global. But to achieve what I think it is you want it should actually be just an instance variable, which is a global in C. They persist across function calls but allow your function to be used in an OO way, so multiple instances can keep their own persistent variables for this particular function.

如果,正如我怀疑的那样,您将类作为单例运行,或者完全像我们开始时的天生程序程序员一样完全静态地运行,@Ellie P 或 @user2626445 的答案将工作正常,因为没有其他实例会搞砸您的全局. 但是为了实现我认为你想要的它实际上应该只是一个实例变量,它在 C 中是一个全局变量。它们在函数调用中持续存在,但允许你的函数以面向对象的方式使用,因此多个实例可以保留自己的此特定函数的持久变量。

Personally, I get around this in jave the same way I get around Hi-Tech C not allowing function bit variables, by declaring the global in the file just above the function declaration. That way me when I hack the code later is less likely to think it's a global and be tempted to mess with it - isn't that why we encapsulate things?

就个人而言,我通过在文件中的函数声明正上方声明全局变量来解决这个问题,就像我解决 Hi-Tech C 不允许函数位变量一样。这样我以后当我破解代码时就不太可能认为它是全局的并且被诱惑去弄乱它 - 这不是我们封装事物的原因吗?