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:

public class Outer {

    private String x = "outer";

    public void outerMethod() {

	final String y = "inner";

	class Inner {
	    public void innerMethod() {
		System.out.println("x = " + x);
		System.out.println("y = " + y);
	    }
	}

	Inner innerTest = new Inner();
	innerTest.innerMethod();

    }
}

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:

public class Outer {

    private String x = "outer";

    public void outerMethod() {

	final String y = "inner";

	Inner innerTest = new Inner() {
	    public void innerMethod() {
		System.out.println("x = " + x);
		System.out.println("y = " + y);
	    }
	};
	innerTest.innerMethod();

    }
}

interface Inner {
    void innerMethod();
}

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

public class Main {

    public static void main(String[] args) {

	Outer test = new Outer();
	test.outerMethod();

    }

}

which generates the output:

x = outer
y = inner

Comments

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.