当使用类型提升的重载时,为什么方法调用是不明确的?

public class aman { void m(double a , int b, int c) { System.out.println("second"); } void m(float a , int b, double c) { System.out.println("first"); } public static void main(String[] args) { aman obj = new aman(); obj.m(23, 12, 1); } } 

这里,方法m()已经重载但我不理解为什么调用是不明确的,因为在第一种方法中只需要进行1次转换,而在第二种方法中,需要进行两次转换。 所以,绝对应该调用第一种方法。 请说明为什么没有发生这种情况或者我错过了一些规则。

JLS不会考虑2次转换和1次转换。 它只会区分必须转换不转换

由于两种方法都必须转换 ,因此它们同样可行。

与此主题相关, 我对类似问题的答案 (但不完全相同)。

这里,方法将是不明确的,因为您将所有参数填充为整数值,然后编译器将混淆(对于自动类型转换)。 因此,您需要为您的代码定义类似此后缀的内容:

 public class aman { void m(double a , int b, int c) { System.out.println("second"); } void m(float a , int b, double c) { System.out.println("first"); } public static void main(String[] args) { aman obj = new aman(); obj.m(20d, 30, 40);//for calling first method obj.m(23f, 12, 1d);//for calling second method. } } 

这里的促销都是可能的,int可以浮动加倍。 所以编译器无法决定调用哪个方法,因此在运行时会产生模糊错误。 方法中的循环孔覆盖类型的自动提升。

 public class Test { void m(int c , int b, int d) { System.out.println("Automatic promotion in overloading--->"+c); } public static void main(String[] args) { Test obj = new Test(); obj.m('A', 30, 40); } } 

这是不明智的,因为你用三个Integer文字调用它。

你必须使用:

 obj.m(23d, 12, 1); 

要么

 obj.m(23, 12, 1f); 

带出任何论据是被通缉的,而且可以提出争论。