HOW TO SET VALUE FOR CONSTANT IN JAVA AFTER DECLARATION?

Lillian Martin

Total Post:27

Points:189
Posted by  Lillian Martin
 1040  View(s)
Ratings:
Rate this:

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?

  1. Mark M

    Post:28

    Points:196
    Re: How to set value for constant in java after declaration?

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

      Modified On Apr-06-2018 05:53:00 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!