Search code examples
javainheritanceaccess-modifiersoverriding

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 Bcreates 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.


Solution

  • 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.