How does the “final” keyword in Java work? (I can still modify an object.)

前端 未结 18 2731
醉酒成梦
醉酒成梦 2020-11-22 03:08

In Java we use final keyword with variables to specify its values are not to be changed. But I see that you can change the value in the constructor / methods of

18条回答
  •  忘掉有多难
    2020-11-22 03:39

    The final keyword can be interpreted in two different ways depending on what it's used on:

    Value types: For ints, doubles etc, it will ensure that the value cannot change,

    Reference types: For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object. It makes no guarantees whatsoever about the values inside the object being referred to staying the same.

    As such, final List foo; ensures that foo always refers to the same list, but the contents of said list may change over time.

提交回复
热议问题