Method return type to fulfill multiple interfaces

后端 未结 4 922
野性不改
野性不改 2021-02-05 08:30

Is it possible to specify a method which returns a object that implements two or multiple interfaces?

Say we have the following interfaces:

interface Foo         


        
4条回答
  •  遥遥无期
    2021-02-05 08:45

    You could return a container to provide Foo and Bar.

    public class Container{
       private FooBarBam foobar;
       public Bar asBar(){
          return foobar;
       }
       public Foo asFoo(){
          return foobar;
       }
    }
    

    This way your code would not have to implement a third interface. Downside is that it is an additional layer of indirection.

    As for why the generic approach does not work: there is no way to provide the type of T and the compiler can't just guess its type, so resolving T is not possible.

    davin's answer looks good but also requires a public class/interface which implements Foo and Bar to work.

    Update:

    The problem is that the compiler does not know that the type of T should be FooAndBarImpl, it would have to guess and a guessing compiler leads to bad and unpredictable code.

    Even a hack using Lists wont compile since the & operator is not supported. While it should be possible to implement it looks like generics currently don't support multiple bounds within return types.

    //Does not compile expecting > after Foo
    List getFooBar(){
        final List l = new ArrayList();
        l.add(new FooAndBarImpl());
        return l;
    } 
    

提交回复
热议问题