2

I have noticed following situation : Inner class is calling method which there is in super class of it and in outer class. Here the code:

 public class Main
    {

        class Inner extends InnerBase{
           public void callMethod(){
               method();
           }
        }

        void method(){
            System.out.println ("Called Main's method");
        }

        class InnerBase{
            void method(){
                System.out.println ("Called InnerBase's method");
            }
        }
    }

Now when callMethod() is calling it calls the method of super class and prints "Called InnerBase's method". If I am trying to 'Open Declaration' from IDE (Eclipse) on method() which is calling in callMethod(), then it goes to method in outer class. It is confusing which one is calling real. Can you suggest or provide some material which explain situation of choosing execution method with same name in outer class and in super class. Thank You in Advance.

Sergey Gazaryan
  • 1,013
  • 1
  • 9
  • 25
  • Let me see if I understand you correctly. You call the Inner.callMethod(), right? So it should call the InnerBase.method(). But you are going to the definition (from the IDE) of Inner.method() and it takes you to Main.method()? – Dandré Dec 06 '12 at 13:14
  • @dandrejvv yes , the IDE don't provide any warning about it – Sergey Gazaryan Dec 06 '12 at 13:22
  • That sounds like a bug in the IDE to me. – Dandré Dec 06 '12 at 13:24

3 Answers3

5

By using a qualified this (JLS §15.8.4. Qualified this), you can specify without any doubt what the selected method will be.

public void callMethod()
{
    Main.this.method();
}

The rule is simple: it will always select the closest method.

InnerBase.method() is part of it own methods. So that is closer than Main.method(), because Main.method() is part of another not-related class. If you had another method() in Inner, then it would select that method, because it is in the same class.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
2

You have three classes here - Main, Inner and InnerBase. Inner is a child of InnerBase, but Main is completely unrelated to them. so, when you call callMethod() on InnerBase, it will ofc call it's OWN method() implementation which it inherits from InnerBase.

If you wanted to call Mains method(), you'd have to explicitly qualify it.

If eclipse jumps to the wrong method, then it is most likely an error of eclipse.

Polygnome
  • 7,639
  • 2
  • 37
  • 57
2

By using "qualified this".

Main.this.method()

See

What does "qualified this" construct mean in java?

Community
  • 1
  • 1
tjltjl
  • 1,479
  • 8
  • 18