Overloaded method selection based on the parameter's real type

后端 未结 7 1389
悲哀的现实
悲哀的现实 2020-11-22 01:39

I\'m experimenting with this code:

interface Callee {
    public void foo(Object o);
    public void foo(String s);
    public void foo(Integer i);
}

class          


        
7条回答
  •  梦毁少年i
    2020-11-22 02:22

    I expect the method selection to take in consideration the real (not the declared) parameter type. Am I missing something?

    Yes. Your expectation is wrong. In Java, dynamic method dispatch happens only for the object the method is called on, not for the parameter types of overloaded methods.

    Citing the Java Language Specification:

    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).

提交回复
热议问题