This is because the inner class executes code only when an event is triggered. If the variable is not declared final, then the MyClass
object referenced in variable
can change, and the inner class will not know which Object it is supposed to be referencing if it needs the MyClass
object.
Thus, it should be declared final so this reference will never change.
Imagine this without the final keyword:
variable
is referencing MyClass
Object with hashCode(): 12345
inner class is created, and variable
in inner class is referencing MyClass
Object with hashCode(): 12345
variable
is changed to be now referencing MyClass
Object with hashCode(): abcde
variable
in inner class is still referencing MyClass
Object with hashCode(): 12345
How does Java run code from here when event is triggered? Use which MyClass
object?
Now with the final keyword:
variable
is referencing MyClass
Object with hashCode(): 12345
inner class is created, and variable
in inner class is referencing MyClass
Object with hashCode(): 12345
Due to the final keyword, the reference cannot be changed.
Java always know which MyClass
object to call when event is triggered. No problems.