如何在Java中创建静态局部变量? [英] How do I create a static local variable in Java?

查看:568
本文介绍了如何在Java中创建静态局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I've read Java does not support static local 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?

推荐答案

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

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

这篇关于如何在Java中创建静态局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆