常量对象与不可变对象 [英] Constant Object vs Immutable Object

查看:114
本文介绍了常量对象与不可变对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在术语不可变对象的位置使用术语常量对象吗?虽然我觉得对象的Immutable是变量的常量,但我不确定这个术语是否被接受。请帮助我理解。

Can I use the term "Constant Object" in the place of the term "Immutable Object"? Though I get the feeling that Immutable for an Object is what Constant is for a variable, I am not sure if this terminology is accepted. Please help me understand.

谢谢,
Karthick S。

Thanks, Karthick S.

推荐答案

事实上,在Java中,术语常量没有明确的含义。它仅在较大的术语编译时常量表达式中出现在JLS中,这是一个可以(并且必须)由编译器而不是在运行时计算的表达式。 (并且保留关键字 const 以允许编译器提供更好的错误消息。)

In fact, in Java the term constant has no defined meaning. It occurs in the JLS only in the larger term compile time constant expression, which is an expression which can (and must) be calculated by the compiler instead of at runtime. (And the keyword const is reserved to allow compilers to give better error messages.)

在Java中,我们改为使用术语 final 来引用无法更改的变量(无论是类,对象还是本地的),以及当我们引用无法更改的对象时引用 immutable 。当谈到变量 x 时,两者都可以使用 - 第一个意味着变量本身(意味着它不能切换到另一个对象),第二个意味着后面的对象变量。因此,这里的两个含义是正交的,并且通常组合在一起以创建真正的常量

In Java, we instead use the term final to refer to variables (whether class, object or local ones) who can't be changed, and immutable when we refer to objects who can't change. Both can be used when speaking about a variable x - the first then means the variable itself (meaning it can't be switched to another object), the second means the object behind the variable. Thus here the two meanings are orthogonal, and are often combined to create a "true constant".

这篇关于常量对象与不可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆