今天在学校上复习课,TA回顾了抽象类的用法,其中有几个重要的知识点之前自己不太懂的,稍微记录一下:
- Once we declare a generic class with type T, we can use instanceof to check if variables are of this type False
关于我们是否可以用instanceof来检测变量的数据类型,答案是不行的。 - 我们是否可以做以下代码
T[] myArray = new T[6];
答案也是否定的。我们不能用抽象类去生成数组。
不过我们可以这么做:
T[] myArray = (T[]) new Object[6];
- 关于 **<? super T>**的使用
首先,这么写的代表 T或者T的supertype(父类)
那么,这么写的好处是什么呢,什么时候可以用到呢,接下来是一个小例子:
class Number implements Comparable<Number> {
public int compareTo(Number n) {
}
}
class naturalNumber extends Number {
} // have the same compareTo method as Number
如果我们不用 <? super T>,如:
public class plane<T extends Comparable<T>> {
}
那么,下一行的代码便是错的
plane <naturalNumber> a = new plane<>();
// 因为naturalNumber 没有 extends Comparable<naturalNumber>
只有使用了
public class plane<T extends Comparable<? super T>> {
}
之前那个代码才是对的。