问题描述
通过扩展或实现链接类时建立子类型。子类型也用于泛型。
A subtype is established when a class is linked by means of extending or implementing. Subtypes are also used for generics.
如何区分子类型和子类?
How can I differentiate subtyping from subclasses?
推荐答案
子类化是一种子类型。
有一个Java允许子类型化的方式:
There are a number of ways Java allows subtyping:
- 当
类A扩展B
时,A
是B
的子类型,因为B b = new A(...);
没问题。 - 当
界面A扩展B
时,A
是B
的子类型,因为B b = new A(){...}
没问题。 - 当
A类扩展B
时,A []
是 B [] 因为B [] b =新A [0]
没问题。 - 当
A类实现B
时,A
是B $的子类型c $ c>因为
B b = new A(...)
没问题。
- When
class A extends B
,A
is a subtype ofB
becauseB b = new A(...);
is ok. - When
interface A extends B
,A
is a subtype ofB
becauseB b = new A() { ... }
is ok. - When
class A extends B
,A[]
is a subtype ofB[]
becauseB[] b = new A[0]
is ok. - When
class A implements B
,A
is a subtype ofB
becauseB b = new A(...)
is ok.
听起来你想要一种方法来区分1和其他人。下面应该这样做。
It sounds like you want a way to distinguish 1 from the others. The below should do that.
static boolean isSubclass(Class<?> a, Class<?> b) {
return !b.isArray() && !b.isInterface() && b.isAssignableFrom(a);
}
但由于类型擦除,它不会处理泛型类的子类型。 类
实例在运行时不携带类型参数,因此无法区分 new ArrayList< String>()的运行时类型
来自新的ArrayList< Integer>()
。
It won't handle subtyping of generic classes due to type erasure though. Class
instances don't carry type parameters at runtime so there is no way to tell at distinguish the runtime type of a new ArrayList<String>()
from a new ArrayList<Integer>()
.
这篇关于子类在哪些方面与使用中的子类不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!