简体   繁体   中英

How does java resolve hidden methods at runtime

Given the following class hierarchy

package pack1;

public class A
{
    private int methodOne(int i)
    {
        return ++i;
    }

    public int methodTwo(int i)
    {
        return methodOne(++i);
    }
}

package pack2;

import pack1.A;

class B extends A
{
    int methodOne(int i)
    {
        return methodTwo(++i);
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        System.out.println(new B().methodOne(101));
    }
}

The output of the above program is 104 . Class B creates its own version of methodOn() because methodOne() is private in Class A . However, during runtime, when inside methodTwo() , the runtime object is of type Class B . Why would java use the methodOne() in class A as oppose of class B .

This is because, despite the name, the two methods are entirely different . methodOne in class B does not override the method with the same name in class A . As you said, B can't see the private methodOne , so it can't possibly override it. So Java creates two separate methods that are not related in any way. Then A 's methodTwo calls the methodOne that's defined in A . If it were public or protected, then other classes might have overridden it, resulting in the late binding we know all too well from Java. However, the methodOne that it sees has never been overridden because B didn't know to do so.

tl;dr : Internally, they're two different and unrelated methods, even though the names are the same.

At very first your code starts executing the code

public static void main(String[] args)
    {
        System.out.println(new B().methodOne(101)); // it invokes methodOne() of class B.
    }

Above code calls methodOne() of class B . Now, MethodOne() is private so it won't override in Class B

Now definition of methodOne() in Class B

int methodOne(int i)
    {
        return methodTwo(++i);  // calling methodTwo() from class A which is a super class of class B.
    }

this code is increase the value of i by 1. So, Now i = 102 . Now again the methodTwo calling the methodOne() of class B in below code.

public int methodTwo(int i) //methodTwo in class A. part of object due to public access modifier.
    {
        return methodOne(++i); // it increase the value of i by 1. Now i =103.
    }

Now the value of i = 103 . Now it calls methodOne() of class A , because methodOne() is private in Class A

private int methodOne(int i)
    {
        return ++i; //again this increase the value of i by 1. Now i =104.
    }

increased the value of i by 1. So, variable i = 104 . So, Final value of i is 104 Now.

So, The Final Output is 104.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM