Shortly I came across an oddity, I can't explain to myself. The real-world problem is already worked around, I'm just curious if there is an satisfying answer I didn't find.
Imagine you have to write a class that implements the following interface from some framework you are using:
interface Interface1 {
String method();
}
So far so good. Now you introduce a second framework and it would be rather useful if your class would implement a second interface:
interface Interface2 {
Long method();
}
That's the point where the problem arises:
class ThatsTheProblem implements Interface1, Interface2 {
public ???? method() {
// ...
}
}
Any ideas?
Just for your information: The real-world problem is based on an abstract-dao-pattern where some entities had Long ids, others had UUID ids.
Short answer: you can't.
What you can do is provide a view that implements one or the other interface. For instance:
public class OnePossibleSolution { // no "implements"
private String interface1Method() {
return "whatever";
}
public Interface1 asInterface1() {
return new Interface1() {
@Override
String method() {
return interface1Method();
}
}
}
// ditto for Interface2...
This is probably the most Java-idiomatic way to solve the problem. It's what Map does when you want to iterate over its elements, for instance. Rather than try to solve the problem of being an Iterable<K>, Iterable<V> and Iterable<Map.Entry<K,V>>, it provides three views:
keySet()values()entrySet()Each of those returns a respective collection, which implements the appropriate Iterable<...> interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With