Sunday 15 March 2015

Setting a value for a constant in Java after declaration -



Setting a value for a constant in Java after declaration -

for simplicity utilize basic example.

if using record (struct) in java programme so:

public class store{ class product{ final int item1; final int item2; final int item3; }

and create constructor class take values represent 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 2 errors:

"the blank final field item1 may not have been initialized

"the final field cannot assigned"

i understand can not re-assign values constants, there way assign values uninitialized constants?

the way assign such values in constructor, need add together constructor construction 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 utilize in rest of code:

public store(int[] elements) { product x = new product(elements[0], elements[1], elements[2]); }

java constants records

No comments:

Post a Comment