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("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) };
        for(Composing c : composing)
            c.dispose();

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)