泛型与扩展 [英] Generics with extends

查看:128
本文介绍了泛型与扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在:

In:

public class Organic<E> {
    void react(E e) {
    }

    static void main(String[] args) {
        Organic<? extends Elem> compound = new Organic<Elem>();
        compound.react(new Elem());
    }
}

class Elem {}

为什么我得到以下编译错误?

Why do I get the following compilation error?


方法 react(capture#1-of?extends Elem )在类型有机<捕获#1中? ( Elem


推荐答案

http ://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

列表是一个有界通配符的例子。这个?代表着未知类型,就像我们之前看到的通配符一样。然而,在这种情况下,我们知道这个未知类型实际上是Shape的一个子类型。 (注意:它可以是Shape本身,也可以是一些子类,它不需要从字面上扩展Shape。)我们说Shape是通配符的上界。

List is an example of a bounded wildcard. The ? stands for an unknown type, just like the wildcards we saw earlier. However, in this case, we know that this unknown type is in fact a subtype of Shape. (Note: It could be Shape itself, or some subclass; it need not literally extend Shape.) We say that Shape is the upper bound of the wildcard.

像往常一样,为了灵活使用通配符而付出代价。这个价格是现在写入方法体内的形状是非法的。例如,这是不允许的:

There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into shapes in the body of the method. For instance, this is not allowed:

public void addRectangle(List<? extends Shape> shapes) {
    // Compile-time error!
    shapes.add(0, new Rectangle());
}

你应该能够弄清楚为什么上面的代码是不允许的。 shapes.add()的第二个参数的类型是?扩展Shape - Shape的未知子类型。由于我们不知道它是什么类型,我们不知道它是否是Rectangle的超类型;它可能或可能不是这样一个超类型,所以在那里传递一个Rectangle是不安全的。

You should be able to figure out why the code above is disallowed. The type of the second parameter to shapes.add() is ? extends Shape-- an unknown subtype of Shape. Since we don't know what type it is, we don't know if it is a supertype of Rectangle; it might or might not be such a supertype, so it isn't safe to pass a Rectangle there.

特别提到你的解决方案,你不能用对象调用react Elem 类型,类型为有机<?扩展Elem> ,你可以合法的分配 compound = new Organic< ElemSubClass>() - 然后反应会导致编译错误,因为你不能称它为传递一个超类对象。

Specifically talking about your solution, you cannot call react with an object of Elem type, as with type Organic<? extends Elem> you can legally assign compound = new Organic<ElemSubClass>() - and then react will cause compile error as you cannot call it passing a super class object.

这篇关于泛型与扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆