public class Foo {
static void test(String s){
System.out.println("String called");
}
static void test(int s){
System.out.println("int called");
}
public static void main(String[] args) throws Exception {
test(5>8? 5:8); // Line 1
test(5>8? "he":"ha"); // Line 2
test(5>8? 5:"ha"); // Line 3
System.out.println(5<8? 5:"ha"); //Line 4
}
}
當我在Line 3
Foo.java:24: error: no suitable method found for test(INT#1)
test(5>8? 5:"ha"); // Line 3
^
三元操作執行此代碼我收到以下錯誤使用類似類型的不給錯誤。但是,使用不同類型的提示錯誤只方法調用但它適用於呼叫System.out.println(5<8? 5:"ha");
當我添加另一個重載方法static void test(Object s){}
,則//Line 3
編譯。
任何人都可以請解釋我這種情況?
很好回答! –
現在我明白如何確定三元運算符的返回類型。根據你的解釋,我想知道方法'System.out.println()'是否有一個重載的方法,它將Object作爲參數,並在PrintStream中找到了一個'public void println(Object x)'方法。如果你可以在你的答案中加入這一點,那麼這對其他人很有用。 –
我覺得這是一個不同的問題。另外,大多數Java程序員都知道他們可以將任何他們喜歡的對象傳遞到'System.out.println'中。 –