Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java snippet output not understood, probably related to polymorphism

I was wondering why this bit of Java yields 2, and not 3 :

public class Test {
    private static class A {
        int f(A a) {
            return 1;
        }
    }
    private static class B extends A {
        int f(A a) {
            return 2;
        }
        int f(B b) {
            return 3;
        }
    }

    public static void main(String[] astrArgs) {
        A ab = new B();
        B b = new B();

        System.out.println( ab.f(b) );  
    }
}

I came across this in a test question, and couldn't get the logic behind it.

like image 891
l0r3nz4cc10 Avatar asked Feb 16 '23 16:02

l0r3nz4cc10


1 Answers

The compile-time type of ab is just A. Therefore, when the compiler sees this expression:

ab.f(b)

... it only considers method signatures declared on A and its superclasses (just Object in this case).

So, the compiler makes the decision to call the method with the signature f(A a).

Now at execution time, the VM chooses which implementation of that signature to execute based on the execution-time type of the target of the method call, which is B.

B overrides f(A a), so that overriding implementation is called - and returns 2.

Basically, overloading is determined at compile-time to work out what method signature to call based on the compile-time types of both the target of the call and the arguments, and overriding is determined at execution-time to work out the exact implementation to execute based on the execution-time type of the target object.

like image 115
Jon Skeet Avatar answered May 10 '23 20:05

Jon Skeet