0

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));
    }
}
fallobst22
  • 63
  • 1
  • 9
  • 4
    `A` doesn't define any `f(int)` method, so obviously, `f(long)` is called in the second case. There is no method overriding in your code . – Arnaud Feb 29 '16 at 16:30

2 Answers2

1

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.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

Actually the subclass B has inherited the method f(with a long) and has added (overloaded) another method f(with a int). When you write down a value such as 1 in such a way the compiler, even before assigning it to a typed reference does parse it as an int. More here: Java's L number (long) specification .

When you call the method f using the reference ab (which is A class) it (the reference) says I can only send you to a method f(with a long) and then implicitly cast the type int 1 into a long.

Let's try to change the type of the method in A class to f(short), then System.out.println(ab.f(1)); will give you this error: "The method f(short) in the type A is not applicable for the arguments (int)"