- 使用了泛型之后是不是就无法使用多态了?如下
public class TwoTuple<A, B> {
public final A first;
public final B second;
public TwoTuple(A a, B b) { first = a; second = b; }
public String toString() {
return "(" + first + ", " + second + ")";
}
}
public class ThreeTuple<A, B, C> extends TwoTuple<A, B> {
public final C third;
public ThreeTuple(A a, B b, C c) {
super(a, b);
third = c;
}
public String toString() {
return "(" + first + ", " + second + ", " + third + ")";
}
}
public class TupleTest {
static TwoTuple<String, Integer> f() {
return new TwoTuple<String, Integer>("hi", 47);
}
static ThreeTuple<Amphibian, String, Integer>g() {
return new ThreeTuple<Amphibian, String, Integer>(new Amphibian(), "hi", 47);
}
public static void main(String... args) {
TwoTuple<String, Integer> ttsi = f();
System.out.println(ttsi);
// ttsi = g();
System.out.println(g());
}
}
函数g()返回ThreeTuple类型,继承自TwoTuple,但是直接赋值的时候会出错。