既然我们能做到
ArrayList<?> l = new ArrayList<Integer>();
我们可以说ArrayList<?>是ArrayList的超类< Integer> ?
上面的例子是否描述了多态性?
更新:通常,如果A< T> B是超T类的T>. , 然后
A<?> obj = new B<Integer>();
然后说A<?>是正确的.是超级B ?
最佳答案 TLDR:
Can we say
ArrayList<?>
is superclass ofArrayList<Integer>
?
不,但我们可以说它是ArrayList的超类型
Then is right to say
A<?>
is super class ofB<Integer>
?
是的,我们也可以说它是B 的超类型.
另请注意,继承仅在子类或超类的上下文中使用,而不是在子类型或超类型中使用.
Quick Reference
您需要了解的第一件事是java中的class is a type.
我们将在下面看到,无论在哪里使用术语sub / super class,使用sub / super类型都是有效的,但反之亦然
现在让我定义超类.根据JLS 8.1.4
Given a (possibly generic) class declaration for
C<F1,...,Fn>
(n ≥ 0,
C ≠ Object) (Fi here is type parameter), the direct superclass of the class typeC<F1,...,Fn>
is
the type given in the extends clause of the declaration of C if an
extends clause is present, or Object otherwise.Let
C<F1,...,Fn>
(n > 0) be a generic class declaration. The direct
superclass of the parameterized class typeC<T1,...,Tn>
, where Ti (1 ≤
i ≤ n) is a type (argument), isD<U1 θ,...,Uk θ>
, whereD<U1,...,Uk>
is the
direct superclass ofC<F1,...,Fn>
, and θ is the substitution
[F1:=T1,…,Fn:=Tn].A class A is a subclass of class C if either of the following is true:
a) A is the direct subclass of C
b)There exists a class B such that A
is a subclass of B, and B is a subclass of C, applying this definition
recursively.Class C is said to be a superclass of class A whenever A is a subclass
of C.
用简单的单词来解释这个问题,请考虑一个更简单的例子:
℃下F1,…,FN>是ArrayList< T>和C< T1,…,Tn>将说ArrayList< Integer>在上面的定义. T是类型参数,我们用Integer实例化它,它是类型参数.
[ What did we meant by θ is the substitution [F1:=T1,…,Fn:=Tn] ? ]
现在,A<?>来自A< Integer>的扩展条款? (我知道问这样的结构是愚蠢的,但让我们严格定义).不,不是的.通常,在扩展中,我们一共提到了不同的类类型.
现在,让我们看看sub / super类型的定义.到JLS 4.10.2
Given a generic type declaration
C<F1,...,Fn>
(n > 0), the direct
supertypes of the parameterized typeC<T1,...,Tn>
, where Ti (1 ≤ i ≤
n) is a type, are all of the following:
D<U1 θ,...,Uk θ>
, whereD<U1,...,Uk>
is a generic type which is a
direct supertype of the generic typeC<T1,...,Tn>
and θ is the
substitution [F1:=T1,…,Fn:=Tn].
C<S1,...,Sn>
, where Si contains Ti (1 ≤ i ≤ n) (§4.5.1).The type Object, if
C<F1,...,Fn>
is a generic interface type with no
direct superinterfaces.The raw type
C
.
现在通过这个定义,根据第2点
C<S1,...,Sn>
, where Si contains Ti (1 ≤ i ≤ n) (§4.5.1).
?包含整数(Reference).因此,这使得A<?> A 的超型.
您可以轻松地看到此定义的第1点,包括子类定义本身.
问题的第二部分,我们已经说过A< T>. B T延伸. ,使它属于两种定义.
最后,我们看到继承意味着什么.到JLS 8.4.8
A class C inherits from its direct superclass all concrete
methods m (both static and instance) of the superclass for which all
of the following are true: […]