2

他のメソッド シグネチャを超えて、このタイプのシグネチャを持つインターフェイスを作成したいと考えています。

Set<Instruction> parse(String rawData);

そして、インターフェイスを実装するクラスでは、実装として行いたい:

 Set<Instruction> parse(String rawData){
   //Do work.
   //return an object of type HashSet<DerivedInstruction>.
 }

抽象クラスをDerivedInstruction拡張する場所。Instruction(代わりに、命令はインターフェースでもかまいません)。

私のポイントは Collection 型ではなく (HashSet が Set を実装していることを知っています)、ジェネリック型です。それを検索したところ、 と の両方がタイプSet<Instruction>HashSet<SpecificInstruction> 拡張し、Object継承を介して関連していないことがわかりました (少なくとも直接ではありません)。したがって、HashSet<SpecificInstruction> 型を返すとアップキャストできません。これを行う方法についてのアイデアはありますか?ありがとうございました。

4

2 に答える 2

8

parseメソッドの型制約を緩和する方法の例を次に示します。

Set<? extends Instruction> parse(String rawData) {
    //....
}

完全な例:

interface Instruction {}
class DerivedInstruction implements Instruction {}

Set<? extends Instruction> parse(String rawData){
    return new HashSet<DerivedInstruction>();
}
于 2013-11-14T13:43:37.800 に答える
1

したがって、返される型で HashSet をアップキャストすることはできません。これを行う方法についてのアイデアはありますか?ありがとうございました。

次に、制限付きワイルドカードの手段を使用する必要があります: Set<? extends Instruction>. は、実際にはそれ自体のサブタイプまたはタイプで?ある未知のタイプを表します。これがワイルドカードの上限であると言います。InstructionInstructionInstruction

Set<? extends Instruction> parse(String rawData){
   //Do work.
   //return an object of type HashSet<DerivedInstruction>.
 }

詳細については、こちらをご覧ください。

于 2013-11-14T13:49:37.857 に答える