forum

Home / DeveloperSection / Forums / How to set value for constant in java after declaration?

How to set value for constant in java after declaration?

Lillian Martin 1974 13-Nov-2014

For simplicity I will use a basic example.

If I am using a record (struct) in my Java program like so:

public class Store{
  class Product{
    final int item1;
    final int item2;
    final int item3;
  }

and I create a constructor for my class that will take values to represent the value of each item:

  public Store(int[] elements) {
     Product x = new Product();
     x.item1 = elements[0];
     x.item2 = elements[1];
     x.item3 = elements[2];
  }
}

The compiler gives me two errors:

"The blank final field item1 may not have been initialized

"The final field cannot be assigned"

I understand that we can not re-assign values to constants, but is there a way to assign values to uninitialized constants?


Updated on 13-Nov-2014

Can you answer this question?


Answer

1 Answers

Liked By