Cannot refer to a non-final variable inside an inner class defined in a different method

前端 未结 20 2716
一向
一向 2020-11-21 05:04

Edited: I need to change the values of several variables as they run several times thorugh a timer. I need to keep updating the values with every iteration through the timer

20条回答
  •  轮回少年
    2020-11-21 05:49

    You can only access final variables from the containing class when using an anonymous class. Therefore you need to declare the variables being used final (which is not an option for you since you are changing lastPrice and price), or don't use an anonymous class.

    So your options are to create an actual inner class, in which you can pass in the variables and use them in a normal fashion

    or:

    There is a quick (and in my opinion ugly) hack for your lastPrice and price variable which is to declare it like so

    final double lastPrice[1];
    final double price[1];
    

    and in your anonymous class you can set the value like this

    price[0] = priceObject.getNextPrice(lastPrice[0]);
    System.out.println();
    lastPrice[0] = price[0];
    

提交回复
热议问题