Final local variable in Inner class in Java 8

Asked

Viewed 179 times

2

There was a modification between Java 7 and 8 versions. Where in Java 7 for a local variable to be used within a inner class should be declared final. Now compiling with Java 8, this local variable is no longer required to be declared final.

Once the Inner Classes needed to access the local variables, they would have to be copied to another memory region in order to become accessible by it, which could generate multiple copies of the same variable and run the risk of having inconsistent data. What led to this change in Java 8, or all my understanding is wrong?

Java Example 7:

public void msgAsync(final String msg){
   java.awt.EventQueue.invokeLater(new Runnable() {
       @Override
       public void run() {
           jText.setText(msg);
       }
   });
}

Java Example 8:

public void msgAsync(String msg){
   java.awt.EventQueue.invokeLater(new Runnable() {
       @Override
       public void run() {
           jText.setText(msg);
       }
   });
}

Both code snippets compile in their respective versions, but note the use of the modifier final only used in Java 7.

1 answer

4


Try making a change in msg and see if compiles.

Java 8 decided to infer the final if there are no changes in the variable, so you do not need to be explicit, but at the bottom even in Java 8 msg is final and continues to require it to be, the difference is that now the compiler knows if it is even without being written.

The variable is effectively final.

  • That’s correct, actually when modified the variable in the Java 8 class Inner, accuses the error, thank you for clarifying.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.