就在我以为我终于理解了泛型的时候,我遇到了下面的例子:
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());
在第二个示例中,允许使用脂肪族及其超类型。那么为什么不允许使用脂肪族?
在第一个例子中,为什么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)
第二个编译器错误:
- The method react(capture#1-of ? super Aliphatic) in the type Organic<capture#1-of ? super Aliphatic> is not applicable for the arguments (Organic)