问题描述
我最近被问过这个问题。但是无法简明扼要地解释这两个概念的确切区别。
I was recently asked this quesion. But was not able to explain concisely what exactly sets both these concepts apart.
例如
最终和不可变:
final String name = "John";
如果我现在写
name = "Sam";
我会收到编译错误
不可变:
String name = "John";
name = "Sam";
它有效。
我认为这解释了应用程序中的一部分。但是,我能否就这两个主题得到一个好的,易于理解的解释?
I think this explains a part of it in application. But can I get a good, easy to understand explanation on both these topic?
推荐答案
final
表示您无法更改对象的引用指向另一个引用或另一个对象,但您仍然可以改变其状态(例如使用setter方法)。 不可变表示无法更改对象的实际值,但您可以将其引用更改为另一个。
final
means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Where immutable means that the object's actual value can't be changed, but you can change its reference to another one.
关于问题的第二部分(不变性部分),编译器使用值创建一个新的 String
对象Sam,并指出名称
对它的引用。
Concerning the second part of your question (immutability part), the compiler creates a new String
object with the value of "Sam", and points the name
reference to it.
这篇关于java中的immutable和final有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!