4
在这个工厂中,返回Component
也实现了一个特殊的接口,在createSomethingSpiffy
中出现错误“类型不匹配:无法从SpiffyCombo转换为C”。返回通用扩展两种类型的工厂方法
我做错了什么,或者是否有必要在这里投SpiffyCombo
到C
?
class Factory {
public static <C extends Component & SpiffyComponent> C createSomethingSpiffy(Object... params) {
C comp = new SpiffyCombo();
// real method will be more complex
return comp;
}
}
class SpiffyTextField extends Component implements SpiffyComponent {
public void wow() { ... }
}
class SpiffyCombo extends JComboBox implements SpiffyComponent {
public void wow() { ... }
}
interface SpiffyComponent {
void wow();
}
如果我们调用'SpiffyTextField foo = Factory。 createSomethingSpiffy()',会发生什么? –
2014-12-03 22:40:36
@SotiriosDelimanolis如果没有任何机会调用它,那么在C Comp = new SpiffyCombo()行中,不能得到这么大的编译错误。而且,实际上,具体的返回类型将由传递给'createSomethingSpiffy'的参数决定。 – 2014-12-03 22:43:11
这就是我的意思。编译器阻止你进入这种情况。 – 2014-12-03 22:46:09