Nic*_*kis 1 java generics collections inheritance
我想创建一个接口,除了其他方法签名之外,它将具有此类型的签名:
Set<Instruction> parse(String rawData);
Run Code Online (Sandbox Code Playgroud)
在实现接口的类中,我想做一个实现:
Set<Instruction> parse(String rawData){
//Do work.
//return an object of type HashSet<DerivedInstruction>.
}
Run Code Online (Sandbox Code Playgroud)
其中DerivedInstruction扩展了Instruction抽象类.(指令也可以是接口,或者).
我的观点不在于Collection类型(我知道HashSet实现Set),而是在泛型类型上.通过在其搜索,我发现,无论Set<Instruction>和HashSet<SpecificInstruction>
扩展Object类型,并通过继承是不相关的(至少不是直接).因此,我无法HashSet<SpecificInstruction> 对返回类型进行预测.关于如何做到这一点的任何想法?谢谢.
下面是一个如何放宽parse方法类型约束的示例:
Set<? extends Instruction> parse(String rawData) {
//....
}
Run Code Online (Sandbox Code Playgroud)
完整的例子:
interface Instruction {}
class DerivedInstruction implements Instruction {}
Set<? extends Instruction> parse(String rawData){
return new HashSet<DerivedInstruction>();
}
Run Code Online (Sandbox Code Playgroud)