Categories
Java

How to access to the members of outer class from inner class

You can’t access to the members of an outer class from an inner class using the keyword “this”.
In fact, the keyword “this” in an inner class is a reference to the inner class itself.
To have a reference to the outer class, you must use the syntax:

[OuterClassName].this

where [OuterClassName] is the name of the outer class.
See the following code as example:

public class OuterClass {

	String myString = new String("outer class");

	void outerMethod() {

		// print the outer class string from the outer class
		System.out.println(this.myString);

		InnerClass innerClass = new InnerClass();
		innerClass.innerMethod();
	}

	class InnerClass {

		String myString = new String("inner class");

		void innerMethod() {

			// print the inner class string from the inner class
			System.out.println(this.myString);

			// print the outer class string from the inner class
			System.out.println(OuterClass.this.myString);
		}
	}
}

Obviously you can’t use “this” from a static code, and this applies as a general rule.

Leave a Reply

Your email address will not be published.

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