我做了一些事情:
class Tuple1<T1, T2> {
private T1 a;
private T2 b;
public Tuple1(T1 a, T2 b) {
this.a = a;
this.b = b;
}
public T1 getA() {
return a;
}
public T2 getB() {
return b;
}
@Override
public String toString() {
return "[" + a.toString() + ", " + b.toString() + "]";
}
}
现在我必须做Tuple2(a,b + c字段)和Tuple3(a,b,c + d字段),它们将具有与Tuple1相同的功能,但没有extends
和没有代码冗余。
最佳答案
您可以创建多个构造函数来执行您想要的操作:
例如:
private T1 a;
private T2 b;
//create a new attribute
private T2 c;
//constructor with two attributes
public Tuple1(T1 a, T2 b) {
this.a = a;
this.b = b;
}
//constructor with three attributes
public Tuple1(T1 a, T2 b, T2 c) {
this.a = a;
this.b = b;
this.c = c;
}
//getters and setters of your attributes
所以当你想使用两个属性时:
Tuple1 t1 = new Tuple1(a, b);
所以当你想使用三个属性时:
Tuple1 t2 = new Tuple1(a, b, c);
您可以在此 Oracle 教程中了解更多信息:Getting Started
关于constructors和 here
希望这可以帮助你。
关于java - 泛型扩展而不扩展 - 如何做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41881274/