In some code I am working with I have an existing third party API that implements things extending from A (and perhaps not directly, but via X, and perhaps also implementing a bunch of other interfaces).
Now for the code I am working on, I have an interface IB, that provides additional capabilities to what A offers. As such a lot of my code actually has the requirement that the object passed to it extends A, and also implements IB, but there is no way to declare that for my member variables I can think of. But picking either A or IB results in a lot of casts.
I guess if A was/had an interface IA would solve this, but there is no way I can change A, or for my implementations of IB to not need to extend A (the third party code uses A, and takes care of a lot of management, persistence, networking, user interfacing, etc. via it).
class Z {
private List<?what here?> items;
/**The implementer of IB should know how to find the Z instance and call this.*/
private void subscribe(? item) {
items.add(item);
}
public void doSomethingWithItems() {
...code thats requires facilities from A and IB...
}
You can specify a type intersection:
<T extends A & IB>
The rules are that if one of the types is a class, it must be listed first.
I would type the class if you can:
class Z<T extends A & IB> {
private List<T> items;
private void subscribe(T item) {
items.add(item);
}
public void doSomethingWithItems() {
// the items are both A and IB
}
}
If you can't type Z, go for typed methods:
class Z {
private List<A>items;
private <T extends A & IB> void subscribe(T item) {
items.add(item);
}
public void doSomethingWithItems() {
// items are A, but if you want IB functionality you must cast.
// the cast is safe if items are only added via subscribe()
}
}
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