泛型扩展无延伸 - 如何做

时间:2017-01-26 19:20:54

标签: 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且没有代码冗余

3 个答案:

答案 0 :(得分:2)

您可以创建多个构造函数,它们可以执行您想要的操作:

例如:

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

希望这可以帮到你。

答案 1 :(得分:1)

您可以为Tuple3制作Tuple2<T1, T2, T3>和类似内容。您将Tuple1<T1, T2>作为私有字段存储在Tuple2中并与T3 c一起存储,并实现所有必需的方法,其中一些方法只是将它们的调用委托给适当的Tuple1方法。它看起来似乎是多余的,但你需要声明一个方法来调用它,所以没有办法避免这种情况。

答案 2 :(得分:1)

您可以考虑以下解决方案:

class Tuple<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() + "]";
    }
}

class Tuple2<T1, T2, T3> 
{
    private Tuple1<T1, T2> tuple;
    private T3 c;

    public Tuple2(T1 a, T2 b, T3 c)
    {
        this.tuple = new Tuple1<T1, T2>(a, b);
        this.c = c;
    }

    public T1 getA() { return tuple.getA(); }

    public T2 getB() { return tuple.getB(); }

    public T3 getC() { return c; }

    @Override
    public String toString()
    {
        return "[" + getA().toString() + ", " + getB().toString() + ", " + c.toString() + "]";
    }
}

class Tuple3<T1, T2, T3, T4> 
{
    private Tuple2<T1, T2, T3> tuple;
    private T4 d;

    public Tuple3(T1 a, T2 b, T3 c, T4 d)
    {
        this.tuple = new Tuple2<T1, T2, T3>(a, b, c);
        this.d = d;
    }

    public T1 getA() { return tuple.getA(); }

    public T2 getB() { return tuple.getB(); }

    public T3 getC() { return tuple.getC(); }

    public T4 getD() { return d; }

    @Override
    public String toString()
    {
        return "[" + getA().toString() + ", " + getB().toString() + ", " + getC().toString() + ", " + d.toString() + "]";
    }
}