0

A extends B

public class Test {

public static void print(A obj) {
    System.out.println("print A");
}

public static void print(B obj) {
    System.out.println("print B");
}

public static void main(String [] args ) {  
    A x = new B();

    print(x);
}

}

Why it'll print "print A"? Why function overloading doesn't look up the real type of x in runtime?

user207421
  • 305,947
  • 44
  • 307
  • 483
kakacii
  • 728
  • 3
  • 10
  • 24

2 Answers2

4

Because overloading is not overriding. The compiler binds methods based on the declared types of arguments.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

Why function overloading doesn't look up the real type of x in runtime?

Because function overloading doesn't look up the real type of x at runtime, by JLS #8.4.9: "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".

user207421
  • 305,947
  • 44
  • 307
  • 483