Java 8接口的默认方法

问题描述:

假设我有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

如果你想实施它们,你为什么需要抽象的?只需要有默认值!但不,这不会编译 –

你可以做这样的事情:

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

仍然不清楚你在问什么,但我添加了所有可能的事情,我可以想到,并可能与您的问题相关:) –