如何避免Java中的构造函数代码冗余?

编程入门 行业动态 更新时间:2024-10-23 15:33:52
本文介绍了如何避免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中的构造函数代码冗余?

本文发布于:2023-11-16 11:49:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1604015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:冗余   函数   代码   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!