Abu*_*kar 5 java null overloading
我在类中重载了以下两种方法:
public class Test{
public static void main(String []args) throws ParseException{
Test t = new Test();
t.testMethod(null);
}
public void testMethod(Object o){
System.out.println("Object");
}
public void testMethod(String s){
System.out.println("String");
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用该方法时,testMethod它会打印"String".
当我再添加一个重载方法时:
public void testMethod(StringBuilder sb){
System.out.println("String");
}
Run Code Online (Sandbox Code Playgroud)
它抛出了编译器错误:The method testMethod is ambigous for type Test..
所有这些都发生在我调用方法时 null
我的问题是:
为什么它打印字符串而不是对象?
java 编译器选择具有最具体或最不通用参数的方法。由于是所有类(包括)Object的超类,因此选择类。StringString
为什么添加第三种方法会出现编译错误?
由于String和StringBuilder位于下面Object,编译器会发现调用不明确,因为 和 都String可以StringBuilder接受null,编译器无法确定要调用哪个方法,因此在编译期间会出现错误。
如果您尝试使用IOExceptionandFileNotFoundException而不是Stringand进行相同的操作StringBuilder,您会发现它FileNotFoundException被选中,因为它最不通用。
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |