ようやくジェネリックを理解したと思ったとき、次の例に出くわしました。
public class Organic<E> {
void react(E e) { }
static void main(String[] args) {
//1: Organic<? extends Organic> compound = new Aliphatic<Organic>();
//2: Organic<? super Aliphatic> compound = new Aliphatic<Organic>();
compound.react(new Organic());
compound.react(new Aliphatic());
compound.react(new Hexane());
} }
class Aliphatic<F> extends Organic<F> { }
class Hexane<G> extends Aliphatic<G> { }
1 行目のコメントを外すと、次のコードはコンパイルされません。
compound.react(new Organic());
compound.react(new Aliphatic());
compound.react(new Hexane());
行 2 がコメント解除されている場合、次のコードはコンパイルされません。
compound.react(new Organic());
2 番目の例では、Aliphatic とそのスーパータイプが許可されています。では、なぜ脂肪族は許可されていないのでしょうか?
最初の例では、なぜnew Organic
許可されないのですか??
最初のコンパイラ エラー:
- The method react(capture#1-of ? extends Organic) in the type Organic<capture#1-of ? extends Organic> is not applicable for the arguments (Organic)
- The method react(capture#2-of ? extends Organic) in the type Organic<capture#2-of ? extends Organic> is not applicable for the arguments (Aliphatic)
- The method react(capture#3-of ? extends Organic) in the type Organic<capture#3-of ? extends Organic> is not applicable for the arguments (Hexane)
2 番目のコンパイラ エラー:
- The method react(capture#1-of ? super Aliphatic) in the type Organic<capture#1-of ? super Aliphatic> is not applicable for the arguments (Organic)