[英]When using overloading with type promotion, why method calling is ambiguous?
public class aman {
void m(double a , int b, int c) {
System.out.println("second");
}
void m(float a , int b, double c) {
System.out.println("first");
}
public static void main(String[] args) {
aman obj = new aman();
obj.m(23, 12, 1);
}
}
這里,方法m()已經重載但我不理解為什么調用是不明確的,因為在第一種方法中只需要進行1次轉換,而在第二種方法中,需要進行兩次轉換。 所以,絕對應該調用第一種方法。 請說明為什么沒有發生這種情況或者我錯過了一些規則。
這里,方法將是不明確的,因為您將所有參數填充為整數值,然后編譯器將混淆(對於自動類型轉換)。 因此,您需要為您的代碼定義類似此后綴的內容:
public class aman {
void m(double a , int b, int c) {
System.out.println("second");
}
void m(float a , int b, double c) {
System.out.println("first");
}
public static void main(String[] args) {
aman obj = new aman();
obj.m(20d, 30, 40);//for calling first method
obj.m(23f, 12, 1d);//for calling second method.
}
}
這里的促銷都是可能的,int可以浮動加倍。 所以編譯器無法決定調用哪個方法,因此在運行時會產生模糊錯誤。 方法中的循環孔覆蓋類型的自動提升。
public class Test {
void m(int c , int b, int d) {
System.out.println("Automatic promotion in overloading--->"+c);
}
public static void main(String[] args) {
Test obj = new Test();
obj.m('A', 30, 40);
}
}
這是不明智的,因為你用三個Integer
文字調用它。
你必須使用:
obj.m(23d, 12, 1);
要么
obj.m(23, 12, 1f);
帶出任何論據是被通緝的,並且可以提出爭論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.