[英]Should I use Objects to avoid method overloading or method overloading is better?
我有兩個接口結構。
public interface MyInterface1{
public Object SUM(Object O,Object P);
}
public interface MyInterface2{
public int SUM(int O,int P);
public double SUM(int O,double P);
public double SUM(double O,double P);
public double SUM(double O,int P);
}
哪種方法可以更好地實現接口,從而保持代碼效率?
第二種方法(重載)更為可取,因為它包含強類型化的方法簽名。
考慮以下代碼。
public class InterfaceImpl implements MyInterface2{
public Object SUM(Object O,Object P){
//Really what can I do here without casting?
/* If I have to cast, I might as well define
types in the method signature, guaranteeing
the type of the arguments
*/
//Lets cast anyway
return (Integer) O + (Integer) P;
}
public static void main(String[] args) throws ParseException {
System.out.println(SUM(1,2)); //Excellent Returns 3
//Yikes, valid arguments but implementation does not handle these
System.out.println(SUM(true,false)); //Class cast exception
}
}
結論
當遇到該方法需要處理的更多類型時,將強制實現在執行必要的強制轉換之前執行類型檢查。 從理論上講,每個擴展Object的類都需要進行類型檢查,因為方法簽名僅約束該類型的參數。 由於參數是對象,因此將檢查無限數量的類型,這是不可能的。
通過使用重載方法,您可以表達方法的意圖並限制允許類型的集合。 這將使編寫該方法的實現更加容易和易於管理,因為參數將被強類型化。
正如已經提到的其他答案一樣,重載更好。
但我還要補充一點,您不需要4個版本,只需2個:
public interface MyInterface2 {
public int SUM(int O, int P);
public double SUM(double O, double P);
}
如果使用(int,double)或(double,int)調用SUM
,則int將被轉換為double,而第二個方法將運行。
例如,下面的代碼編譯並打印“再見”:
public class Test implements MyInterface2 {
public int SUM(int o, int p) {
System.err.println("hello");
return o + p;
}
public double SUM(double o, double p) {
System.err.println("goodbye");
return o + p;
}
public static void main(String[] arg) {
Test t = new Test();
t.SUM(1.0, 2);
}
}
在這種情況下,第二種選擇是好的。 但是它隨代碼的不同而不同。 例
interface InterfaceFrequencyCounter
{
int getCount(List list, String name);
}
interface AnotherInterfaceFrequencyCounter
{
int getCount(ArrayList arrayList, String name);
int getCount(LinkedList linkedList, String name);
int getCount(Vector vector, String name);
}
因此,在上述情況下,第二種選擇不是一種好習慣。 第一個是好的。
重載更好,因為您不希望有人使用String
或其他名稱來調用您的方法。
你可以做什么,如果你(有一個是使用一個共同的超類Number
-如果你想獲得長期和浮動過你的情況)。
對於安全的代碼方法,重載是更好的方法。
如上所述,過載更好。
如果遇到AmitG描述的情況,則應使用接口,而不僅僅是最通用的對象類型。 無論如何,您的方法幾乎總是只能與部分對象(而不是全部)一起正常工作。 在那種情況下,您需要找到一個通用接口並將其用於方法簽名中,就像AmitG在他的示例中所做的那樣。 接口的使用清楚地表明了您對方法的意圖,它是類型安全的,並且不需要在方法內部進行強制轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.