当前位置:   article > 正文

java string 重载,JAVA Object / String方法重载

函数重载时,object和string 调用时会走哪个?

Just out of curiosity I tried this example.

public class Class1 {

public void method(Object obj){

System.out.println("Object");

}

public void method(String str){

System.out.println("String");

}

public static void main(String... arg){

new Class1().method(null);

}

}

The output being "String". I want to know on what basis the JVM decides to invoke method taking String as argument and not Object.

解决方案

Whenever more than one overloaded methods can be applied to the argument list, the most specific method is used.

In this case either of the methods can be called when passing null, since the "null type" is assignable to both Object and to String. The method that takes String is more specific so it will be picked.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/468096
推荐阅读
相关标签
  

闽ICP备14008679号