Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Runtime choose the invocation method between outer class method and super class?

Tags:

java

oop

jvm

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.

like image 433
Sergey Gazaryan Avatar asked Jul 28 '26 05:07

Sergey Gazaryan


1 Answers

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.

like image 157
Martijn Courteaux Avatar answered Jul 30 '26 20:07

Martijn Courteaux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!