ShaDiliX ShaDiliX - 11 months ago 104
Java Question

Constructor Chain

Why do we use this form? (it's on a course on plural sight for Java)

public MathEquation(char opCode)
{
this.opCode = opCode;
}

public MathEquation(char opCode , double leftVal , double rightVal)
{
this(opCode);
this.leftVal = leftVal;
this.rightVal = rightVal;
}


and why not this?

public MathEquation(char opCode , double leftVal , double rightVal)
{
this.opCode = opCode
this.leftVal = leftVal;
this.rightVal = rightVal;
}

Answer Source

Because if, for some reason, you need to do something more with the opCode (like turning it to uppercase before storing it, or check it's in some range, or anything like that), you won't have to repeat that code in the two constructors. One will simply invoke the code already written in the other.

This general principle is called DRY: Don't Repeat Yourself.

Note that it's often being made in the other direction: the simplest constructor calls the most complex one, specifying what default values to pass for the missing arguments:

public MathEquation(char opCode) {
    this(opCode, 0.0, 0.0);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download