Sign in to follow this  
Fred304

[java] accessing "this" of enclosing class?

Recommended Posts

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;
		}
	}
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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 ;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this