Final (Java): Difference between revisions

Content deleted Content added
m Restored text that was mistakenly removed
Final and inner classes
Line 75:
 
Like full [[immutability]], finality of variables has great advantages, especially in optimization. For instance, <code>Sphere</code> will probably have a function returning its volume; knowing that its radius is constant allows us to [[Memoization|memoize]] the computed volume. If we have relatively few <code>Sphere</code>s and we need their volumes very often, the performance gain might be substantial. Making the radius of a <code>Sphere</code> <code>final</code> informs developers and compilers that this sort of optimization is possible in all code that uses <code>Sphere</code>s.
 
===Final and inner classes===
 
When an anonymous [[inner class]] is defined within the body of a method, all variables declared <code>final</code> in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the <code>final</code> variable cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its [[call stack|stack frame]] has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.
 
<source lang="Java">
import javax.swing.*;
 
public class FooGUI {
 
public static void main(String[] args) {
//initialize GUI components
final JFrame jf = new JFrame("Hello world!"); //allows jf to be accessed from inner class body
jf.add(new JButton("Click me"));
// pack and make visible on the Event-Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jf.pack(); //this would be a compile-time error if jf were not final
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
}
}
}
</source>
 
===Blank final===