Jump to content
  • Advertisement
Sign in to follow this  
Fred304

[java] accessing "this" of enclosing class?

This topic is 4497 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
Hey bud,

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

Dave

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!