Java 最终变量是否随时间变化其值?
我目前在一本教科书上自学Java,发现了一段我不懂的代码——为什么最后一个变量Java 最终变量是否随时间变化其值?,java,final,Java,Final,我目前在一本教科书上自学Java,发现了一段我不懂的代码——为什么最后一个变量id会改变它的值 import static net.mindview.util.Print.*; class Shared { private int refcount = 0; private static int counter = 0; private final int id = counter++; public Shared() { print("
id
会改变它的值
import static net.mindview.util.Print.*;
class Shared {
private int refcount = 0;
private static int counter = 0;
private final int id = counter++;
public Shared() {
print("Creating " + this);
}
public void addRef() { refcount++; }
protected void dispose() {
if(--refcount == 0)
print("Disposing " + this);
}
protected void finalize() {
if(refcount != 0)
print("Error: object is not properly cleaned-up!");
}
public String toString() { return "Shared " + id; }
}
class Composing {
private Shared shared;
private static int counter = 0;
private final int id = counter++;
public Composing(Shared shared) {
print("Creating " + this);
this.shared = shared;
this.shared.addRef();
}
protected void dispose() {
print("disposing " + this);
shared.dispose();
}
public String toString() { return "Composing " + id; }
}
public class E13_VerifiedRefCounting {
public static void main(String[] args) {
Shared shared = new Shared();
Composing[] composing = { new Composing(shared),
new Composing(shared), new Composing(shared),
new Composing(shared), new Composing(shared) };
for(Composing c : composing)
c.dispose();
这:
与此相同:
private static int counter = 0;
private final int id;
public Shared() {
id = counter++;
print("Creating " + this);
}
也就是说,每次构造函数执行时都会分配id
,其副作用是计数器
递增
id
是一个实例变量,因此shared
的每个实例都有自己的id
值
private final int id = counter++;
如果通过更改,您询问为什么
id
的值是counter+1
而不是counter
,这是因为首先计算计数器+1的和,然后将其设置为id
。之后,id的值不能更改。为什么说id变量是final?我只是从未翻译版本的书中复制粘贴了代码,有一个id变量没有final前缀(什么?)所以我把它改成了final,就像我在这本书的版本中一样。这是书中原始代码的代码,所以我猜放在那里的final只是一个错误?不,final
意味着变量a)必须在ctor中赋值,b)不能在ctor中或之后重新赋值。这不是错误,它工作正常。好的,构造函数中的id初始化对我来说更清晰,非常感谢!但是计数器
的旧值设置为id
private final int id = counter++;