簡體   English   中英

為什么不支持不同返回類型的重載

[英]why overloading with different return type is not supported

我已經搜索並發現使用不同的返回類型進行重載是不可能的,但我嘗試這樣做並且我確實得到了輸出。

public class inte {

    public int add(int a, int b) {
        return a + b;
    }
    
    public double add(int c, int d, int e) {
        return c + d + e;
    }
    
    public static void main(String args[]) {
        inte i = new inte();
        double sum=i.add(1, 2, 3);
        System.out.println(sum);
    }
}

這返回了正確的輸出:

6.0

像這樣重載是可能的,因為您更改了參數。 僅更改返回類型而沒有其他任何事情是行不通的,因為編譯器無法僅根據返回類型來決定選擇哪一個。 但是,由於方法具有不同的參數,編譯器可以選擇正確的方法。 更多關於重載在這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM