Getting the variables of the outer class from an inner class

The inner classes, and then not static, can access even if with some limitation to the variables of the outer class.

Consider the following example:

Here the inner class Inner isn’t only inside the class but it is also inside the method outerMethod().
It can access to the member variable x even if it is declared private and it can access to the local variable y only because it is declared final.
If the variable y is not declared final the code will not compile and would return the error:
“Cannot refer to a non-final variable y inside an inner class defined in a different method …”

A similar situation also occurs for anonymous classes:

To test the class Outer you need a method main():

which generates the output:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.