So i have a JList and i am trying to use it inside of a JButtons actionPerformed method and it is asking me to make the JList final why is that, below is a code snippet
public SomeClass() {
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
list.clearSelection();
}});
}
I don’t actually have a problem making it final, I just am not sure why i would need to.
To answer your question, you need to understand the basics, as to how the JVM use to work.
When the classes are compiled which contain inner classes, the byte code which gets generated does not actually implement inner classes as a class within a class.
WHY THE ERROR : The local variable was accessed from an inner class, needs to declare it final
When you compile your this program, two files will be created, Foo.class and Foo$1.class. So now your problem comes, since the
Secondclass i.e.foo$1.classdoesn’t know thatVariableedit is present inside theFirstclass i.e.foo.class.So how to solve this problem ? What
JVMdoes, is that, It makes a requirement for the developer to make the variable of an outer class to be declared as final.Now this being done, now JVM quietly places a hidden variable with the name val$edit inside the 2nd compiled class file, here is the output as got from
javapOuput for foo.class
Now since, edit is local to the constructor, hence the output as above.
The
Variableval$edit is assigned the same value which has been assigned to edit since now the compiler knows that the value cannot be changed as it has been declared final and hence it works this time.Now what if I change the edit
Variablefrom beingLocalto beingInstance. Now the object of the class knows everything about this variable edit, if it gets changed. So changing the above program likewise we get :Here in this case, we are not suppose to declare and define it as being
final, because in this case since theVariablebeing Local to the whole class, theVariableis send to the Inner Class along with theObject Referencei.e.thisHere is how the
Variableis send in this case i.e. this$0 :Seems like that the interpretation, how this situation works, according to me.
Just now I found this wonderful explanation on the internet regarding Mystery of Accessibility in Local Inner Classes, might be this will help you understand the situation in a much better way 🙂