How is ambiguity in selecting from overloaded methods resolved in Java?

前端 未结 5 1113
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 15:48
package org.study.algos;
public class Study {

    public static void main(String[] args) {
       A a = new A();
       a.m1(null);
    }
 }
 class A {
    public v         


        
5条回答
  •  旧巷少年郎
    2020-11-28 16:08

    These methods are "overloaded", not "ambiguous".

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

    And §15.12.2 says:

    There may be more than one such method, in which case the most specific one is chosen.

    String is more specific than Object, so while null is compatible with both, the method with the String parameter is chosen (there are much more complex rules that apply when the parameter types are part of a class or interface hierarchy).

提交回复
热议问题