声明后在Java中设置常量的值

时间:2014-10-24 03:38:09

标签: java constants records

为简单起见,我将使用一个基本的例子。

如果我在我的Java程序中使用记录(struct),那么:

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可能尚未初始化

“无法分配最终字段”

我知道我们不能将值重新赋值给常量,但有没有办法为未初始化的常量赋值?

2 个答案:

答案 0 :(得分:2)

唯一的方法是在构造函数中分配这样的值,因此您需要在结构类中添加构造函数:

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

}

答案 1 :(得分:1)

你可以这样做:

class Store {
    public Store(int[] element) {
        Product p = new Product(element[0], element[1], element[2]);
    }

    class Product {
        final int item1;
        final int item2;
        final int item3;

        public Product(int item1, int item2, int item3) {
            this.item1 = item1;
            this.item2 = item2;
            this.item3 = item3;
        }
    }
}
相关问题