Quick tip: How to call parent outer class methods from an inner class

A friend of mine asked me about this and googled: “java inner class parent methods”. Hopefully this will help other Java programmers who run into this same problem.

[By the way, I neither condone nor promote these naming conventions. :) ]

Say you have an interface Foo, with a method bar().

Also say that you have a FooImpl class that implements Foo with a method bar(), and inside of it you have a NodeImpl inner class that also implements Foo, which means that it too has a method bar(). Say that NodeImpl also has another method doSomething(), which needs to call bar(), but specifically the bar() of the parent, FooImpl.

Problem: If you just call bar() from inside the inner class NodeImpl, you will get the inner class’s bar(). This is because of scoping. So how do you solve this?

Answer: Call FooImpl.this.bar() or in general, call ParentClass.this.method() from your inner class.

This entry was posted in Desktop Java. Bookmark the permalink.

4 Responses to Quick tip: How to call parent outer class methods from an inner class

  1. Zigmar says:

    Thanks for tip, just what I’ve been looking for!

  2. Jasmine says:

    Just the information I needed, thank you! :)

  3. Steve says:

    Nice! I have been trying to figure out how to do that for a long time now.

    Thanks!
    Steve

  4. simon says:

    just what I needed ;)