编辑:我需要更改几个变量的值,因为它们通过计时器运行几次.我需要通过计时器每次迭代不断更新值.我无法将值设置为final,因为这会阻止我更新值,但是我收到了我在下面的初始问题中描述的错误:
我以前写过以下内容:
我收到错误"不能引用在不同方法中定义的内部类中的非final变量".
这种情况发生在双重调用价格和价格调用priceObject上.你知道我为什么会遇到这个问题.我不明白为什么我需要最后的声明.此外,如果你能看到我想要做的是什么,我该怎么做才能解决这个问题.
public static void main(String args[]) {
int period = 2000;
int delay = 2000;
double lastPrice = 0;
Price priceObject = new Price();
double price = 0;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
price = priceObject.getNextPrice(lastPrice);
System.out.println();
lastPrice = price;
}
}, delay, period);
}
Run Code Online (Sandbox Code Playgroud) 我知道方法变量存储在内存的堆栈上但稍有混淆final.我曾浏览像许多环节这无法得到正确的认识?下面是的例子inner class,其中final变量被访问,本地non-final变量不因为它们被存储在stack
class Employee {
public void getAddress(){
final int location = 13;
int notFinalVar = 13;
class Address {
System.out.println (location);
System.out.println (notFinalVar); // compiler error
}
}
Run Code Online (Sandbox Code Playgroud)
更新:刚才开始知道隐藏的字段叫做synthetic field(inner class heap memory area),其中存储了最终变量的副本,所以它最终意味着最终的变量存储在最后Stack memory Area?
Local Inner类不仅可以访问实例变量,还可以访问方法的局部变量(在其中定义它们),但必须声明局部变量final.
为什么final在这种情况下必须声明局部变量?