KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Is it possible to specify a method which returns a object that implements two or multiple interfaces? Say we have the following interfaces: interface FooBar { [Foo] & [Bar] getFooBar(); } interface Foo { void doFoo(); } inteface Bar { void doBar(); } Implementors of FooBar need to provide the method getFooBar() that returns an instance of a type which fullfills Foo as well as Bar . What I tried so far is to do it with generics: interface FooBar { <T extends Foo & Bar> T getFooBar() } class SomeImplementor implements FooBar { private FooAndBarImpl fSomeField; public <T extends Foo & Bar> T getFooBar() { return fSomeField; } } Given that FooAndBarImpl is some type provided by a framework or library and implements Foo and Bar this I think should work. However, it doesn't, because "FooAndBarImpl cannot be converted to T". Why is that? The contract implied by getFooBar() is not broken as I see it. Another solution would be to define a new interface that extends Foo and Bar and to use that as return type. I just don't see much sense in returning a empty wrapper for the fSomeField in the getFooBar() implementation. EDIT: Would appreciate it if someone could explain why the generics approach doesn't work. I just don't see it.
Tags (comma-separated)
Save Edits
Cancel