如何避免Java中的构造函数代码冗余? [英] How to avoid constructor code redundancy in Java?

查看:171
本文介绍了如何避免Java中的构造函数代码冗余?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

class Pair
{
    String car;
    Integer cdr;

    public Pair () {}
    public Pair (String car) { this.car = car; }
    public Pair (Integer cdr) { this.cdr = cdr; }

    public Pair (String car, Integer cdr)
    {
        this(car);
        this(cdr);
    }
}

该类包含两个可选值,我想提供所有可能的构造函数排列。第一个版本没有初始化任何东西,第二个版本只初始化第一个值,第三个版本只初始化第二个值。

The class contains two optional values and I would like to provide all possible constructor permutations. The first version does not initialize anything, the second initializes only the first value and the third initializes only the second value.

最后一个构造函数是第二个和第三个的组合一。但是不可能把它写下来,因为代码失败了。

The last constructor is the combination of the second and third one. But it is not possible to write this down, because the code fails with.


constructor.java:13: call to this must be first statement in constructor
        this(cdr);
            ^
1 error

是否可以编写最后一个没有任何代码冗余的构造函数(也可以不调用相同的setter方法)?

Is it possible to write the last constructor without any code redundancy (also without calling the same setter methods)?

推荐答案

通常,参数较少的构造函数应该调用那些具有更多参数的构造函数。

As a rule, constructors with fewer arguments should call those with more.

public Pair() {}
public Pair(String car) { this(car, null); }
public Pair(Integer cdr) { this(null, cdr); }
public Pair(String car, Integer cdr) { this.car = car; this.cdr = cdr; }

这篇关于如何避免Java中的构造函数代码冗余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆