gpt4 book ai didi

java - 泛型扩展而不扩展 - 怎么做

转载 作者:行者123 更新时间:2023-11-30 06:50:01 28 4
gpt4 key购买 nike

我做了一些事情:

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

关于constructorshere

希望对您有所帮助。

关于java - 泛型扩展而不扩展 - 怎么做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41881274/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com