user3274263 user3274263 - 5 months ago 22
Java Question

Programming trick: not able to modify variable before constructor call

public final Class MoneyI implements Money {

public MoneyI(int a, Currency b) {
}

public MoneyI(int a, String b) {
b= b.equals("A")?"B":b;
this(a, Currency.getInstance(b));
}
}


Obviously the second constructor will throw error saying that this should be the first statement in a constructor call.

How can I then modify the string before the call? I cant do
new moneyI(a, Currency.getInstance(b))
because it will create a new instance of MoneyI and not modify in the same call.

Answer

You can simply not change the string itself before the constructor call, but send the "correct" value in the call itself (and then, if you still need to modify the parameter, do it):

public final Class MoneyI implements Money {

    public MoneyI(int a, Currency b) {
    }

    public MoneyI(int a, String b) { 
        this(a, Currency.getInstance(b.equals("A") ? "B" : b));
        b = b.equals("A") ? "B" : b;
    }

}