在这个工厂中,它返回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();
}
类型参数实际上只在调用站点中有用(+/- 少数情况)。在类型参数的范围内,类型基本上是其边界。因此,尽管SpiffyCombo
符合C
的界限,但并不是每个绑定到C
的可能类型都是SpiffyCombo
。因此,编译器不能让您互换使用两者的值。
你似乎想实现类似的东西
abstract class HellaSpiffyComponent extends Component implements SpiffyComponent {}
public static HellaSpiffyComponent createSomethingSpiffy(Object... params) {...}
并使相应的类扩展HellaSpiffyComponent
而不是扩展Component
和实现SpiffyComponent
。