Java Anonymous Inner Classes and Effectively Final variables

compile error

Anonymous Inner Class

According to Oracle Java docs, anonymous classes are defined as

Anonymous Inner Classes and Final variables

In the code snippet shown below, I have created a Integer list and to iterate over the list, instead of using the default iterator provided by the ArrayList class, I have created my own custom iterator where we will iterator over only even numbers in that list.

But why not access local variables that are not final or effectively final?

While compiling, Java compiler creates two class files, one class file for the “AnonymousTest” class containing the main method show above and another one for the inner anonymous iterator class we have created and instantiated inside the main method.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store