[java] accessing "this" of enclosing class?

Started by
2 comments, last by Monkeyget 18 years ago
A (non-static) inner class has access to its enclosing class's fields and methods. But what about the "this" pointer of the enclosing class? An inner class surely must have a pointer to its enclosing class. I have come up with a generel pattern, but is there an easier way?

public class Foo
{
	private Foo foo;
	
	public Foo()
	{
		foo = this;
	}
	
	public class Bar
	{
		public Foo getFoo()
		{
			return foo;
		}
	}
}
Advertisement
Hey bud,

first of all, why do you want the this of the contained class?

Dave
Easy...
Foo.this

As for why one would need this, if the inner class calls on a function that requires an instance of the enclosing class, this is perfect.
Quote:Original post by Dave
Hey bud,

first of all, why do you want the this of the contained class?

Dave

It may be useful. You create another class AND it can access all the private methods of the outer class.


There is a nice and fun article explaining the what's and why's of inner classes here : http://www.javaranch.com/campfire/StoryInner.jsp
I especially like the end of the article ;)

This topic is closed to new replies.

Advertisement