gpt4 book ai didi

java - 编程技巧: not able to modify variable before constructor call

转载 作者:行者123 更新时间:2023-12-01 09:45:40 26 4
gpt4 key购买 nike

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));
}
}

显然,第二个构造函数会抛出错误,表明这应该是构造函数调用中的第一个语句。

如何在调用之前修改字符串?我无法执行 new MoneyI(a,Currency.getInstance(b)) 因为它将创建 MoneyI 的新实例,并且不会在同一调用中进行修改。

最佳答案

您可以在构造函数调用之前不更改字符串本身,而是在调用本身中发送“正确”值(然后,如果您仍然需要修改参数,请执行此操作):

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;
}

}

关于java - 编程技巧: not able to modify variable before constructor call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38067491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com