簡體   English   中英

Java 8 接口中的默認方法

[英]default method in Java 8 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;
    }
}

你可以這樣做:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM