就在我以爲我終於明白了泛型,我碰到下面的例子就是:泛型超與延伸
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