I have the following class:
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
Is it possible to write the last constructor without any code redundancy (also without calling the same setter methods)?
The use of feature branches can help to prevent redundant code getting checked into the main code branch.
Constructor Overloading - Multiple Constructors for a Java Class. A class can have multiple constructors, as long as their signature (the parameters they take) are not the same. You can define as many constructors as you need.
Code redundancy occurs when a character or group of characters in a code word can be partially or completely deduced from the remaining characters of the code word.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With