In a school test I used non final variables inside an anonyme inner class. On the the school Computer and on my private Computer(using x86 jre1.8.0_45) it is working.
However, on the teachers Laptop Eclipse is showing errors (The variables should use final). He is using jre1.8.0.x version (don't know the exact version).
Any ideas why it is working on my computer and not on his computer?
In this code example the no final object jLabel is used inside the actionPerformed function of the ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
public class Main {
public Main(String[] args) {
JLabel jLabel = new JLabel();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jLabel.setText("xyz");
}
});
}
}
Newer java versions are more tolerant in this concern: they only require that they should be "effectively final".
At the end, the difference is not soo big - you only can use variables which you COULD tag with final; you may not modify them.
If you are at that place, you as well can make them "really" final, and it works everywhere.
BTW, on 1.8 with its new lambda syntax you can write more elegantly
button.addActionListener((ActionEvent arg0) -> jLabel.setText("xyz"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With