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
在這種情況下,解決方案已在下列進行演示 −
示例
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 值。現在,呼叫這個例項,並將先前定義的引數作為引數傳遞。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
JavaScript
PHP