Java中的矛盾和继承有什么区别?

问题描述 投票:0回答:1

我有一个父类A,而它的子类B。这两个摘要之间有什么区别:

    public static void main (String[] args) {
        ArrayList<? super A> e = new ArrayList<>();
        B thing = new B();
        e.add(thing);
        System.out.println(e.get(0));
    }
    public static void main (String[] args) {
        ArrayList<A> e = new ArrayList<>();
        B thing = new B();
        e.add(thing);
        System.out.println(e.get(0));
    }
java list inheritance contravariance
1个回答
3
投票

ArrayList<? super A>ArrayList<A>之间的区别在于,可以为前者分配ArrayList<T>的对象,其中TAA本身的超类。

具体来说,这是有效的:

ArrayList<? super A> listOfSuperA = new ArrayList<Object>();

这不是:

ArrayList<A> listOfA = new ArrayList<Object>();

这意味着您可以从listOfAlistOfSuperA中获得不同类型的值:

A a = listOfA.get(0); // valid
Object o = listOfA.get(0); // valid, because A can be converted to Object.
A a2 = listOfSuperA.get(0); // invalid, because listOfSuperA could contain Objects, which are not convertible to A
Object o2 = listOfSuperA.get(0); // valid, because whatever is in listOfSuperA, it can be converted to Object

This might be useful if you want to learn more about where to use ? super T

© www.soinside.com 2019 - 2024. All rights reserved.