因为我们可以做到
ArrayList<?> l = new ArrayList<Integer>();
我们可以说 ArrayList<?>
是 ArrayList<Integer>
的父类(super class)?
上面的例子是否因此描述了多态性?
更新:一般来说,如果A<T>
是 B<T>
的父类(super class), 然后
A<?> obj = new B<Integer>();
那么说对了A<?>
是 B<Integer>
的父类(super class)?
最佳答案
TLDR:
Can we say
ArrayList<?>
is superclass ofArrayList<Integer>
?
NO 但我们可以说它是 ArrayList<Integer>
的父类(super class)型
Then is right to say
A<?>
is super class ofB<Integer>
?
YES 我们也可以说它是 B<Integer>
的父类(super class)型
另请注意,继承仅用于子类或父类(super class)的上下文中,而不用于子类型或父类(super class)型。
首先你需要了解的是class is a type在 java 。 我们将在下面看到,只要有效使用术语 sub/super class ,使用 sub/super type 都是有效的,但反之则不然
现在让我定义父类(super class)。根据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.
为了用简单的词来解释这件事,考虑一个更简单的例子:
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>
的扩展子句中? (我知道问这样的结构是愚蠢的,但让我们严格定义)。不,不是的。通常,在 extends 中我们会提到完全不同的类类型。
现在,让我们看看子/父类(super class)型的定义。通过 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).
?
包含 Integer
(Reference)。因此,这使得 A<?>
A<Integer>
的父类(super class)型.
你可以很容易地看到这个定义的第 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: [...]
关于java - Java 中通配符泛型的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42993354/