Java 中的方法重载和 null 错误


当 Java 中的方法被重载时,这些函数具有相同的名称,而且该函数的参数数量相同。在这种情况下,如果参数是非原始类型并且能够接受 null 值,那么当该函数使用 null 值调用时,编译器会感到疑惑,因为它无法选择其中任何一个,因为两者都能够接受 null 值。这会导致编译时错误。

示例

下面是一个展示这种情况的例子 −

实时演示

public class Demo {
   public void my_function(Integer i) {
      System.out.println("The function with integer as parameter is called ");
   }
   public void my_function(String name) {
      System.out.println("The function with string as parameter is called ");
   }
   public static void main(String [] args) {
      Demo my_instance = new Demo();
      my_instance.my_function(null);
   }
}

输出

/Demo.java:15: error: reference to my_function is ambiguous
my_instance.my_function(null);
^
both method my_function(Integer) in Demo and method my_function(String) in Demo match
1 error

在这种情况下,解决方案已在下列进行演示 −

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

示例

实时演示

public class Demo {
   public void my_function(Integer i) {
      System.out.println("The function with integer as parameter is called ");
   }
   public void my_function(String name) {
      System.out.println("The function with string as parameter is called ");
   }
   public static void main(String [] args) {
      Demo my_instance = new Demo();
      String arg = null;
      my_instance.my_function(arg);
   }
}

输出

The function with string as parameter is called

一个名为 Demo 的类包含一个名为“my_function”的函数,该函数采用一个整数作为参数。该函数被重载,且参数为一个字符串。当调用这两个函数中的任何一个时,会在屏幕上打印相关消息。在 main 函数中,创建 Demo 类的一个实例,并且将一个字符串类型参数指定为 null 值。现在,调用这个实例,并将先前定义的参数作为参数传递。

更新于:2020 年 9 月 14 日

716 次浏览

助力你的职业发展

完成课程获得认证

开始学习
广告