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.

4 Replies to “Quick tip: How to call parent outer class methods from an inner class”

Comments are closed.