Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java inner classes require "final" outer instance variables? [duplicate]

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?

like image 520
Adham shafik Avatar asked Oct 11 '10 22:10

Adham shafik


People also ask

Why do we need inner class can't we just work with outer classes wherever 6 we implement inner classes?

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.

What are the main disadvantages of using Java inner classes?

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.

What is the relationship between instances of the inner class and instances of the outer class?

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.

Does outer class variables are accessible in inner class?

In inner classes, variables of outer class are accessible, but local variables of a method are not.


1 Answers

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.

like image 169
Pointy Avatar answered Oct 11 '22 15:10

Pointy