就在我以为我终于明白了泛型,我碰到下面的例子就是:泛型超与延伸
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 ucommented,以下将不编译:
compound.react(new Organic());
在第二考试PLE,脂肪族和它的超类型是允许的。那么,为什么不允许脂肪含量?
在第一示例中,为什么不能new Organic
允许?
1编译器错误:
- 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)
第二编译器错误:
- The method react(capture#1-of ? super Aliphatic) in the type Organic<capture#1-of ? super Aliphatic> is not applicable for the arguments (Organic)
您是否尝试过这个自己,你得到了什么编译器错误? –
我知道我得到了什么,我不明白为什么。 – Maggie
[Java中的 super T>和 extends T>之间的区别]的可能的重复](http://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java) – dimo414