Search code examples
javafunctionvirtual

Java virtual function calls


From my understanding all function-calls in Java are virtual, and numeral literals have the type int. But why does the Output in the example below differ?

public class A {
    public int f(long d) {
        return 2;
    }
}
public class B extends A {
    public int f(int d) {
        return 1;
    }
}
public class M {
    public static void main(String[] args) {
        B b = new B();
        A ab = b;
        System.out.println(b.f(1));
        System.out.println(ab.f(1));
    }
}

Solution

  • You dont override anything.

    • The first calling System.out.println(b.f(1)); returns 1, because it works with class B, even the method is named same, but parameters are different (long is not the same as int).

    • In case when parameters are same (int d), the result would be 1, because it overrides (@Override) the method from the class A.

    • Now, you know why the second calling System.out.println(ab.f(1)); returns 2. Look from what class it's called from.