Java overloading and inheritance rules

Solution 1:

The behavior of these method calls is dictated and described by the Java Language Specification (reference section 8.4.9).

When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).

In your example, the Java compiler determines the closest match on the compile type of the instance you are invoking your method on. In this case:

A.method(AX)

The closest method is from type A, with signature A.method(A). At runtime, dynamic dispatch is performed on the actual type of A (which is an instance of AX), and hence this is the method that is actually called:

AX.method(A)

Solution 2:

I will clarified it in more simple way. See when you making sub class object with super class reference like here you did.

Always one thing keep in your mind that when you call with super class reference, no matters object is of sub class it will go to the super class, check method with this name along with proper signature is there or not.

now if it will find it, than it will check whether it is overridden?? if yes than it will go to the sub class method like here it went. another wise it will execute the same super class method.

I can give you the example of it...just hide

public int method(A a) {
        return 3;
    }

method & check your answer you will get 1 2 1 2, why because it gives first priority to reference. because you overridden it & than calling it, so its giving 3..!! hope its big but easy to understand. Happy Learning

Solution 3:

a2 referenced as an A and the JVM using the reference first (not the acutal object as you expected).