亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 方法重載——在某些情況下將方法合并為一個方法?

Java 方法重載——在某些情況下將方法合并為一個方法?

慕勒3428872 2023-10-13 16:29:48
雖然我了解方法重載的重要性,但我很好奇是否可以為以下代碼編寫單個添加函數:public class Add {    public int add(int i, int j) {        return i + j;    }    public double add(double i, double j) {        return i + j;    }}
查看完整描述

3 回答

?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

另一個答案行不通,但如果我們稍微修改一下,它就可以工作:


public Number add(Number i, Number j) {

    if(i instanceof Integer && j instanceof Integer) {

        return i.intValue() + j.intValue();

    } else if(i instanceof Double && j instanceof Double) {

        return i.doubleValue() + j.doubleValue();

    } //you can check for more number subclasses

    return null; //or throw and exception

}   

但這比超載要丑陋得多。


查看完整回答
反對 回復 2023-10-13
?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

您可以采用通用方法,而不是重載。


public static class Utils {


public static <T extends Number> Number multiply(T x, T y) {

    if (x instanceof Integer) {

        return ((Integer) x).intValue() + ((Integer) y).intValue();

    } else if (x instanceof Double) {

        return ((Double) x).doubleValue() + ((Double) y).doubleValue();

    }

    return 0;

   }

}

并像這樣使用它


Utils.<Double>multiply(1.2, 2.4); // allowed

Utils.<Integer>multiply(1.2, 2.4); // not allowed

Utils.<Integer>multiply(1, 2); // allowed


查看完整回答
反對 回復 2023-10-13
?
holdtom

TA貢獻1805條經驗 獲得超10個贊

當然有可能。首先,double 函數可以接受 int 值,因此如果需要,您可以將其用于兩者。但是,如果您仍然想實現目標,最好的方法是使用泛型。另一種方法是讓您的方法接受兩個類的父類(例如 Object),然后進行適當的轉換,如下所示:


public class Add {


   enum ParamType {

       INT,

       DOUBLE

   }


   public static Object add(Object i, Object j, ParamType paramType) {

       if (paramType.equals(ParamType.INT)) {

           return (int) i + (int) j;

       } else {

           return (double) i + (double) j;

       }

   }


   public static void main(String[] args) {

       System.out.println(add(3.4, 5.2, ParamType.DOUBLE));

       System.out.println(add(3, 5, ParamType.INT));

   }

}


查看完整回答
反對 回復 2023-10-13
  • 3 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號