final JTextField jtfContent = new JTextField(); btnOK.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent event){ jtfContent.setText("I am OK"); } } );
If I omit final
, I see the error "Cannot refer to a non-final variable jtfContent inside an inner class defined in a different method".
Why must an anonymous inner class require the outer classes instance variable to be final in order to access it?
Inner classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. Nested classes can lead to more readable and maintainable code because it logically group classes in one place only.
Inner classes have their disadvantages. From a maintenance point of view, inexperienced Java developers may find the inner class difficult to understand. The use of inner classes will also increase the total number of classes in your code.
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.
In inner classes, variables of outer class are accessible, but local variables of a method are not.
Well first, let's all relax, and please put that gun down.
OK. Now the reason the language insists on that is that it cheats in order to provide your inner class functions access to the local variables they crave. The runtime makes a copy of the local execution context (and etc. as appropriate), and thus it insists that you make everything final
so it can keep things honest.
If it didn't do that, then code that changed the value of a local variable after your object was constructed but before the inner class function runs might be confusing and weird.
This is the essence of a lot of the brouhaha around Java and "closures".
Note: the opening paragraph was a joke in reference to some all-caps text in the original composition of the OP.
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