假設我有3種方法(相同的名稱,不同的參數,相同的返回類型),有沒有一種方法可以定義一個實現3種方法的默認方法(在我的例子中爲Foo
)?Java 8接口的默認方法
以前實現
public interface testFoo {
public int Foo (int a);
public int Foo (int a, int b);
public int Foo (int a, int b, int c);
}
新的實施,
public interface testFoo {
default public int Foo (int a) {
return a+1;
}
default public int Foo (int a, int b) {
return b+1;
}
default public int Foo (int a, int b, int c) {
return c+1;
}
}
你是什麼意思實現3種方法?如果這是你需要的,你可以調用其他的抽象方法 –
@ bali182,我的意思是如果有一種方法可以爲3個重載方法實現一個默認方法?我張貼我的代碼澄清。我的更新代碼對每個重載方法都有3個默認方法,並且想知道一個解決方案是否爲3個重載方法定義了一個默認方法?謝謝。 –
如果你想實施它們,你爲什麼需要抽象的?只需要有默認值!但不,這不會編譯 –