Method return type to fulfill multiple interfaces

后端 未结 4 975
野性不改
野性不改 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:44

    You can make T a class parameter:

    class SomeImplementor implements FooBar {
        private T fSomeField;
    
        public T getFooBar() {
            return fSomeField;
        }
    
    }
    

    As to why your generics approach didn't work. Lets create the following two classes that implement Foo and Bar:

    class A implements Bar, Foo{
       private int a;
       ...
    }
    class B implements Bar, Foo{
       private String b;
       ...
    }
    class SomeImplementor implements FooBar {
       private A someField;
       public  T getFooBar() {
          return someField;
       }
    }
    

    So we should now be able to execute the following:

    SomeImplementor s = new SomeImplementor();
    A a = s.getFooBar();
    B b = s.getFooBar();
    

    Although getFooBar() returns an object of type A, which has no valid cast to type B (where will the String member come from?), even though B fulfills the requirement of , i.e. is a valid T.

    In short, the compiler (remember, generics is a compile-time mechanism) can't guarantee that every T of type can have an assignment to it of type A. Which is exactly the error you see - the compiler can't convert the given A to every valid T.

提交回复
热议问题