Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Java doesn't support true <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" rel="noreferrer">closures</a>, even though using an anonymous class like you are using here (<code>new TimerTask() { ... }</code>) looks like a kind of closure.</p> <p><strong>edit</strong> - <em>See the comments below - the following is not a correct explanation, as KeeperOfTheSoul points out.</em></p> <p>This is why it doesn't work:</p> <p>The variables <code>lastPrice</code> and price are local variables in the main() method. The object that you create with the anonymous class might last until after the <code>main()</code> method returns.</p> <p>When the <code>main()</code> method returns, local variables (such as <code>lastPrice</code> and <code>price</code>) will be cleaned up from the stack, so they won't exist anymore after <code>main()</code> returns.</p> <p>But the anonymous class object references these variables. Things would go horribly wrong if the anonymous class object tries to access the variables after they have been cleaned up.</p> <p>By making <code>lastPrice</code> and <code>price</code> <code>final</code>, they are not really variables anymore, but constants. The compiler can then just replace the use of <code>lastPrice</code> and <code>price</code> in the anonymous class with the values of the constants (at compile time, of course), and you won't have the problem with accessing non-existent variables anymore.</p> <p>Other programming languages that do support closures do it by treating those variables specially - by making sure they don't get destroyed when the method ends, so that the closure can still access the variables.</p> <p>@Ankur: You could do this:</p> <pre><code>public static void main(String args[]) { int period = 2000; int delay = 2000; Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { // Variables as member variables instead of local variables in main() private double lastPrice = 0; private Price priceObject = new Price(); private double price = 0; public void run() { price = priceObject.getNextPrice(lastPrice); System.out.println(); lastPrice = price; } }, delay, period); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload