gam*_*ver 51 java static scope
我读过Java不支持static本地变量,不像C/C++.现在,如果我想用一个局部变量编写一个函数,其值应该在函数调用之间保持不变,我该怎么做?
我应该使用实例变量吗?
Ell*_* P. 33
您可以拥有一个静态类变量,该变量将在该类的所有实例中保留.如果那是你想要的.如果不是,请使用实例变量,该变量仅在此对象的方法调用之间保留.
public class Foo {
static int bar;
//set bar somewhere
public int baz() {
return 3 * bar;
}
}
Run Code Online (Sandbox Code Playgroud)
如果要在函数调用之间重用变量值并将此变量与其他方法隔离,则应将其封装在对象中.首先,定义一个只包含"类似静态"变量的类和您需要的函数:
class MyFunctionWithState {
private int myVar = 0;
public int call() {
myVar++;
return myVar;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,从您的客户端代码:
class Foo {
private MyFunctionWithState func = new MyFunctionWithState();
public int bar() {
return func.call();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果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() { /*...*/ }
}
Run Code Online (Sandbox Code Playgroud)
局部变量是方法中的变量.只有方法才能访问这些变量.您不能拥有静态局部变量,但可以使用实例变量或类变量.
如果您的方法是静态的,默认情况下会为所有对象创建此方法的副本,并且无法进一步细分,因为局部变量仅限制它们访问它们所在的方法.
| 归档时间: |
|
| 查看次数: |
82296 次 |
| 最近记录: |