2014-12-03 74 views
4

在这个工厂中,返回Component也实现了一个特殊的接口,在createSomethingSpiffy中出现错误“类型不匹配:无法从SpiffyCombo转换为C”。返回通用扩展两种类型的工厂方法

我做错了什么,或者是否有必要在这里投SpiffyComboC

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(); 
} 
+0

如果我们调用'SpiffyTextField foo = Factory。 createSomethingSpiffy()',会发生什么? – 2014-12-03 22:40:36

+0

@SotiriosDelimanolis如果没有任何机会调用它,那么在C Comp = new SpiffyCombo()行中,不能得到这么大的编译错误。而且,实际上,具体的返回类型将由传递给'createSomethingSpiffy'的参数决定。 – 2014-12-03 22:43:11

+0

这就是我的意思。编译器阻止你进入这种情况。 – 2014-12-03 22:46:09

回答

0

一个类型参数实际上只在调用站点(+/-几个例子)中才有用。在类型参数的范围内,类型基本上是其边界。因此,虽然SpiffyCombo符合C的界限,但不是与C绑定的每种可能类型都是SpiffyCombo。因此,编译器不能让你使用可互换的值。

你似乎想实现像

abstract class HellaSpiffyComponent extends Component implements SpiffyComponent {} 

public static HellaSpiffyComponent createSomethingSpiffy(Object... params) {...} 

,让您相应的类扩展HellaSpiffyComponent,而不是延长Component和实施SpiffyComponent