让我们看下面的例子:
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
}
}
如果我希望BothPaintAndPrintable
将实例添加到每个 ArrayLists 怎么办?一种方法是使用BothPaintAndPrintable
参数重载方法,但我正在尝试寻找替代方案,因为这样做可能会降低代码的可重用性。有人有其他想法吗?