getPump
が返したPump
は、Pump<T>
ではない可能性があります。 を返します。U
は、Inflatable
に拡張されたものです。 T
がU
のサブタイプであると仮定することは安全ではありません。
Inflatable
:C1
とC2
を実装する2つの具体的なクラスがあるとしましょう。 getPump
は、Pump<C1>
のインスタンスを返すことがあります。 T
がC2
であるとします。タイプC2
のオブジェクトはC1
のインスタンスではないため、readPressure
メソッドに渡すことはできません。
そのため、タイプセーフティ違反なしで「修正」できないのはこのためです。ここで
は、あなたが間違ったことをやろうとしていることを示す具体的な例です:あなたが行うことができます
class C1 implements Inflatable, Pump<C1> {
@Override
public Pump<? extends Inflatable> getPump() {
return this; // an instance of C1 which implements Pump<C1>
}
@Override
public int readPressure(C1 thingToInflate) {
return 0;
}
}
class C2 implements Inflatable {
@Override
public Pump<? extends Inflatable> getPump() {
return new C1(); // again, an instance of C1 which implements Pump<C1>
}
}
public class Preparer {
public <T extends Inflatable> void inflate(T thingToInflate) {
int pressure = thingToInflate.getPump().readPressure(thingToInflate);
// Let's assume that it were possible. What happens if one calls
// new Preparer().inflate(new C2())?
// new C2().getPump() returns an instance of C1 which implements Pump<C1>
// It's readPressure method expects an instance of C1. But T = C2, so
// the thingToInflate is not an instance of C1.
// If the compiler allowed this to happen, the type safety
// would be violated.
}
}
唯一のことは、あなたのインターフェイスを再設計されています。私はあなたのコードが最初に達成しようとしているものがわからないので、修正する正確な方法を教えてくれません。
あなたが予期している用途が 'int readPressure(Inflatable)'を示唆しているので、 'Pump'は実際には一般的ではないはずです。おそらく[PECS](https://stackoverflow.com/q/2723397/2891664)も参照してください。 – Radiodef