2016-09-29 122 views
-2

假設我有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; 
    } 
} 
+1

你是什麼意思實現3種方法?如果這是你需要的,你可以調用其他的抽象方法 –

+0

@ bali182,我的意思是如果有一種方法可以爲3個重載方法實現一個默認方法?我張貼我的代碼澄清。我的更新代碼對每個重載方法都有3個默認方法,並且想知道一個解決方案是否爲3個重載方法定義了一個默認方法?謝謝。 –

+1

如果你想實施它們,你爲什麼需要抽象的?只需要有默認值!但不,這不會編譯 –

回答

1

你可以做這樣的事情:

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 TestFooTrait extends 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; 
    } 
} 

class TestFooImpl implements TestFooTrait { 
    // I don't have to impelemt anything :) 
} 

您也可以自由使用您的摘要方法默認值:

interface FooWithDefault { 
    public default int Foo (int a) { 
     return Foo(a, 1, 1); 
    } 

    public default int Foo (int a, int b) { 
     return Foo(a, b, 1); 
    } 

    // Let implementations handle this 
    public int Foo (int a, int b, int c); 
} 
+0

嗨bali182,我更新後與我以前的實施和新實現,在我的新實現中,我實現了3個默認方法,想知道是否有解決方案來實現1默認方法來覆蓋3重載'Foo'方法?我目前的解決方案是使用3個默認方法,每個重載'Foo'方法。在你的代碼中,你仍然有3個默認方法。 –

+0

我問是否有辦法爲所有重載方法實現一個默認方法,因爲我正在處理的接口有數十個重載方法,想查看是否有簡化解決方案爲所有重載實現添加一個默認方法。 –

+1

仍然不清楚你在問什麼,但我添加了所有可能的事情,我可以想到,並可能與您的問題相關:) –