LoginSignup
14
13

More than 5 years have passed since last update.

戻り値の型のみが異なるメソッドを持つ複数のインタフェースを実装する

Last updated at Posted at 2016-01-12

戻り値の型のみが異なるメソッドを持つインタフェースが複数あったとします。
通常これらのインタフェースを同時に実装したり拡張したりすることはできません。

コンパルエラー
    interface A { int foo(); }
    interface B { String foo(); }
    interface AB extends A, B { }
エラー: 型Bと型Aが適合していません両方ともfoo()を定義していますが戻り値の型が無関係です
    interface AB extends A, B { }
    ^
エラー1個

戻り値の型がともにインタフェースである場合も同様です。

コンパイルエラー
    interface X {}
    interface Y {}
    interface A { X foo(); }
    interface B { Y foo(); }
    interface AB extends A, B {}
エラー: 型Bと型Aが適合していません両方ともfoo()を定義していますが戻り値の型が無関係です
    interface AB extends A, B {}
    ^
エラー1個

ただし後者の場合は両方の戻り値の型を拡張するインタフェースを定義するとコンパイルできるようになります。

コンパイルOK
    interface X {}
    interface Y {}
    interface A { X foo(); }
    interface B { Y foo(); }
    interface XY extends X, Y {}
    interface AB extends A, B { XY foo(); }

あるいは両方の戻り値の型を実装するクラスであっても構いません。

コンパイルOK
    interface X {}
    interface Y {}
    interface A { X foo(); }
    interface B { Y foo(); }
    class XY implements X, Y {}
    interface AB extends A, B { XY foo(); }

絶対できないと思ってStackoverflowで質問したら回答があったのでびっくりしました。
How can I implement Function and BiFunction at the same time?

14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13