[英]Can we say that the reference variable pointing to an immutable object is a constant variable?
I have a doubt from one of the answers in stackoverflow to the following question: 我有一个疑问从一个答案在计算器到以下问题:
How many String objects are created by the following code? 以下代码创建了多少个String对象?
String x = new String("xyz");
String y = "abc";
x = x + y;
In Stephen's answer he mentioned x and y are not constant variables. 在斯蒂芬的回答中,他提到x和y不是常数。
My doubt- String is a final class, and it's instance will be a constant because String is an immutable class. 我的疑问-字符串是一个最终类,并且它的实例将是一个常量,因为字符串是一个不可变的类。 Why is the reference variable of this constant class not a constant variable?
为什么此常量类的引用变量不是常量变量? - I do agree with Stephen though as
x = x + y;
-我确实同意斯蒂芬的观点,因为
x = x + y;
points at "xyzabc" created in the heap memory. 指向在堆内存中创建的“ xyzabc”。
There are a few concepts that you need to understand. 您需要了解一些概念。
Marking a class as final
does not make it immutable. 将一个类标记为
final
不会使它不变。 It just makes it un-inheritable. 它只是使其不可继承。
JLS §8.1.1.2
JLS§8.1.1.2
A class can be declared final if its definition is complete and no subclasses are desired or required.
如果一个类的定义完整并且不需要或不需要子类,则可以将其声明为final。
It is a compile-time error if the name of a final class appears in the extends clause (§8.1.4) of another class declaration;
如果最终类的名称出现在另一个类声明的extends子句(第8.1.4节)中,则是编译时错误。 this implies that a final class cannot have any subclasses.
这意味着最终类不能有任何子类。
A class is said to be immutable when the values that it stores cannot be changed after initialisation. 当初始化后无法更改其存储的值时,该类被称为不可变的。
A constant variable is a variable marked with final
. 常数变数是标有
final
的变数。
JLS §4.12.4
JLS§4.12.4
A variable can be declared final.
可以将变量声明为final。 A final variable may only be assigned to once.
最终变量只能分配一次。 Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.
声明变量final可作为有用的文档,其值不会改变,并有助于避免编程错误。
It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.
如果将最终变量赋值给它,则是编译时错误,除非在赋值之前肯定未赋值(第16节)。
x
and y
here are not constants because they are not marked final
. x
和y
此处不是常量,因为它们未标记为final
。 That's it . 就是这样 。
"But strings can't change, so they are constants, right?" “但是字符串不能改变,所以它们是常量,对吗?” you might ask.
你可能会问。
String
objects themselves can't change, but string variables can . String
对象本身不能更改,但字符串变量可以更改。 I'll show you: 我会给你看:
String s = "Hello";
s = "Goodbye";
The variable's value is changed so that it refers to another string. 更改变量的值,使其引用另一个字符串。 The original string "Hello" is not changed.
原始字符串“ Hello”未更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.