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

前端 未结 18 2303
醉酒成梦
醉酒成梦 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:33

    You are always allowed to initialize a final variable. The compiler makes sure that you can do it only once.

    Note that calling methods on an object stored in a final variable has nothing to do with the semantics of final. In other words: final is only about the reference itself, and not about the contents of the referenced object.

    Java has no concept of object immutability; this is achieved by carefully designing the object, and is a far-from-trivial endeavor.

提交回复
热议问题