"对于 Y 类型,方法 X 含混不清" Java 含混不清的方法调用 null 错误

如果你正在阅读这篇文章,那么你可能会在编译一个Java程序时在终端或任何Java IDE中遇到方法X对于Y类型的错误是模糊的

Java 模糊的方法调用

在这里,我将解释为什么Java模糊的方法调用错误有一些例子。这个模糊的方法调用错误总是伴随着方法过载,编译器无法找出哪一种过载的方法应该使用。

 1package com.journaldev.errors;
 2
 3public class Test {
 4
 5    public void foo(Object o) {
 6    	System.out.println("Object");
 7    }
 8
 9    public void foo(String s) {
10    	System.out.println("String");
11    }
12    public static void main(String[] args) {
13    	new Test().foo(null);
14    }
15
16}

上面的程序完美地编译,当我们运行它时,它打印了字符串。所以程序称之为foo(String s)的方法。 这个原因是 Java 编译器试图用最具体的输入参数来找出该方法来调用一种方法。 我们知道 Object 是 String 的母类类,所以选择很容易。

如果多于一个成员方法既可访问又可应用于方法召唤......Java编程语言使用的是选择最具体的方法的规则。

我通过null的原因是因为它适用于任何类型的参数,如果我们通过任何其他对象,Java编译器的方法选择很容易。

X 方法对于 Y 类型来说是模糊的。

现在让我们将下面的方法添加到上面的代码中。

1public void foo(Integer i){
2    System.out.println("Integer");
3}

You will get compile time error as The method foo(Object) is ambiguous for the type Test because both String and Integer class have Object as parent class and there is no inheritance. So java compiler doesn't consider any of them to be more specific, hence the method ambiguous call error.

 1package com.journaldev.strings;
 2
 3public class Test {
 4
 5    public void foo(Object o) {
 6    	System.out.println("Object");
 7    }
 8
 9    public void foo(Exception e) {
10    	System.out.println("Exception");
11    }
12
13    public void foo(NullPointerException ne) {
14    	System.out.println("NullPointerException");
15    }
16
17    public static void main(String[] args) {
18    	new Test().foo(null);
19    }
20
21}

如上所述,这里‘foo(NullPointerException ne)’是最具体的方法,因为它是从例外类继承的,因此这个代码编译得很好,当执行时打印NullPointerException

Published At
Categories with 技术
Tagged with
comments powered by Disqus