为了简单起见,我将使用一个基本示例。
如果我在 Java 程序中使用记录(结构),如下所示:
public class Store{
class Product{
final int item1;
final int item2;
final int item3;
}
我为我的类创建一个构造函数,它将采用值来表示每个项目的值:
public Store(int[] elements) {
Product x = new Product();
x.item1 = elements[0];
x.item2 = elements[1];
x.item3 = elements[2];
}
}
编译器给了我两个错误:
“空白的最终字段 item1 可能尚未初始化
“无法分配最终字段”
我知道我们不能为常量重新赋值,但是有没有办法为未初始化的常量赋值?
最佳答案
唯一的方法是在构造函数中分配此类值,因此您需要向结构类添加构造函数:
class Product{
Product(double item1, double item2, double item3) {
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
}
final double item1;
final double item2;
final double item3;
}
然后在其余代码中使用它:
public Store(int[] elements) {
Product x = new Product(elements[0], elements[1], elements[2]);
}
关于java - 在声明后为 Java 中的常量设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26541087/