子类在哪些方面与使用中的子类不同? [英] In what ways are subtypes different from subclasses in usage?

查看:140
本文介绍了子类在哪些方面与使用中的子类不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过扩展或实现链接类时建立子类型。子类型也用于泛型。

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:


  1. 类A扩展B 时, A B 的子类型,因为 B b = new A(...); 没问题。

  2. 界面A扩展B 时, A B 的子类型,因为 B b = new A(){...} 没问题。

  3. A类扩展B 时, A [] 是<的子类型 B [] 因为 B [] b =新A [0] 没问题。

  4. A类实现B 时, A B 因为 B b = new A(...)没问题。

  1. When class A extends B, A is a subtype of B because B b = new A(...); is ok.
  2. When interface A extends B, A is a subtype of B because B b = new A() { ... } is ok.
  3. When class A extends B, A[] is a subtype of B[] because B[] b = new A[0] is ok.
  4. When class A implements B, A is a subtype of B because B 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>().

这篇关于子类在哪些方面与使用中的子类不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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