I learn java from book “Java. How to Program” P. & H. Deitel
On page 216 there is an example which used final in one of variable
private static final Random randomNumbers = new Random();
As far as I understand declaration final in variable mean, that variable is kind of constant, that mean when is initialized you cant change it anymore.
But above object(variable) is used in program twice to return random number
int die1 = 1 + randomNumbers.nextInt( 6 );
int die2 = 1 + randomNumbers.nextInt( 6 );
and it returns 2 different (random) values.
I think I lost something here. Program works good, but I dont understand what was purpose to use final in object declaration?
finalmeans that the variable cannot change its value here – and indeed it can’t and doesn’t.Here the value of the
randomNumbersvariable is a reference to an instance ofRandom. It refers to the same instance, even though that instance produces (potentially) different numbers each time you callnextInt.It’s important to differentiate between a variable not changing value, and the object it refers to not changing internal state. As another example, you could have something like this:
Here we only have one list – you can never change
friendsto refer to a different object – but we can still mutate the list that the variable refers to.