java – 重载方法如何工作?

前端之家收集整理的这篇文章主要介绍了java – 重载方法如何工作?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. public class Test1 {
  2.  
  3. public static void main(String[] args) {
  4. Test1 test1 = new Test1();
  5. test1.testMethod(null);
  6. }
  7.  
  8. public void testMethod(String s){
  9. System.out.println("Inside String Method");
  10. }
  11.  
  12. public void testMethod(Object o){
  13. System.out.println("Inside Object Method");
  14. }
  15. }

当我尝试运行给定的代码时,我得到以下输出

Inside String Method

任何人都可以解释为什么使用String类型参数的方法调用

解决方法

最重要的方法选择最具体的方法参数

在这种情况下,String是Object的子类.因此String变得比Object更具体.因此,打印了Inside String方法.

直接从JLS-15.12.2.5

If more than one member method is both accessible and applicable to a method invocation,it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

正如BMT和LastFreeNickName正确提示的那样,(Object)null将引起使用Object type方法的重载方法调用.

猜你在找的Java相关文章