本人学艺不精,在看下面的程序时有几点疑问希望大家能指教一下,多谢。
1、关于程序的执行顺序请大家指教我理解的是否正确。首先找到主类,检查是否有基类,若存在,先加载基类,初始化基类的static变量->变量->构造器,然后再加载导出类,初始化导出类的static变量->变量->构造器。而本例没有继承关系,使用的是组合。因此,首先执行main()里的Shared shared=new Shared(),此时转到Shared类初始化static的counter,然后顺序初始化refcount、id、Shared(),最后生成shared对象。同理生成composing[]数组对象。最后用for语句消除每个对象。
2、两次final long id 的定义。这两次定义的是对象的引用吧?如果将id赋予确切的数值就是基本类型的定义,id就变成常量了?或者说id定义的是对象引用还是常量,区别在于赋予它的初值,如果是counter就是对象引用,如果是7就是常量,对吗?
3、关于for(Composing c : composing)。是将每个composing赋给c,也就是c和composing[i]指向的是同一块区域,相当于一个人有两个名字,这样理解对吗?class Shared {
private int refcount=0;
private static long counter=0;
private final long id=counter++;
public Shared() {
System.out.print("Creating "+this);
}
public void addRef() { refcount++; }
protected void dispose() {
if(--refcount==0)
System.out.print("Disposing "+this);
}
public String toString() { return "Shared " +id; }
}class Composing {
private Shared shared;
private static long counter=0;
private final long id=counter++;
public Composing(Shared shared) {
System.out.print("Creating "+this);
this.shared=shared;
this.shared.addRef();
}
protected void dispose() {
System.out.print("disposing "+this);
shared.dispose();
}
public String toString() { return "Composing "+id; }
}public class ReferenceCounting {
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();
Shared s2=new Shared();
Shared s3=new Shared();

}
}