Lets look at the following example:
public class BothPaintAndPrintable implements Paintable,Printable{
public void print() {}
public void paint() {}
}
public interface Paintable {
public void paint();
}
public interface Printable {
public void print();
}
public class ITest {
ArrayList<Printable> printables = new ArrayList<Printable>();
ArrayList<Paintable> paintables = new ArrayList<Paintable>();
public void add(Paintable p) {
paintables.add(p);
}
public void add(Printable p) {
printables.add(p);
}
public static void main(String[] args) {
BothPaintAndPrintable a= new BothPaintAndPrintable();
ITest t=new ITest();
t.add(a);//compiliation error here
}
}
What if I want BothPaintAndPrintable instances to be added to each of the ArrayLists?
One way would be overloading the method with a BothPaintAndPrintable parameter, but I’m trying to see alternatives since doing that might reduce code reuseability. Does anyone have another idea?
You need a third overload:
This makes the erasure
add(Object), so it doesn’t conflict with the other methods, but it does restrict the input to implementors of bothPaintableandPrintable.(Guava had to use this trick for
JoinerwithIteratorandIterable, because some evil classes out there implemented both, even though it’s a terrible idea.)