Java 8界面中的默认方法

时间:2016-09-29 19:42:19

标签: java interface

假设我有3个方法(同名,不同参数,相同的返回类型),有没有办法可以定义一个默认方法来实现3个方法(在我的例子中为Foo)?

以前的实施

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 个答案:

答案 0 :(得分: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);
}