java - 泛型扩展而不扩展 - 如何做

标签 java extends redundancy

我做了一些事情:

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/

相关文章:

java - 测试行为与实现

java - SOLR documentCache JMX 指标澄清

Java向父类(super class)添加变量

azure - 最大限度地减少停机时间(Azure 网站 + SQL DB)

Firefox 52.4.1 上的 Java Applet "ClassNotFoundException"- 适用于 IE

java - 使用 java 中的 ocpsoft 重写删除 .xhtml 扩展名

java - 不使用 extends 的 Java 中的可扩展枚举

java - Java中关于多个类的继承

java - 如何在多个面板中使用一个类

c++ - 如何从多重 map 中删除项目