0

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?

jean
  • 973
  • 1
  • 11
  • 23
  • 1
    `final` variable can not be modified. it must be initialized at the time of declaration. – Rustam Oct 24 '14 at 03:41
  • You can initialize your final within your class. That is what you should do. So create a constructor that does that. – Alvin Bunk Oct 24 '14 at 03:42
  • 1
    `Product x = new Product;` is this statement correct? – Rustam Oct 24 '14 at 03:42
  • 2
    Note that Java doesn't have structs. While you can get the same effect by creating an object with no methods, it's still a full-fledged object. Forgive me if I'm assuming, but when you say "struct" I infer that you don't have a lot of experience with Java objects. Try not to think of them as structs and you'll probably have a better time. – dimo414 Oct 24 '14 at 03:47

2 Answers2

4

The only way is to assign such values in the constructor, so you would need to add a constructor to your structure class:

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

And then use it in the rest of your code:

public Store(int[] elements) {

    Product x = new Product(elements[0], elements[1], elements[2]);

}
morgano
  • 17,210
  • 10
  • 45
  • 56
1

you can do like this:

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;
        }
    }
}
Rustam
  • 6,485
  • 1
  • 25
  • 25