これは、「Thinking in Java」の章「Resuing Classes」の Ex18 からのものです。コードは次のとおりです。
public class E18 {
public static void main(String[]args)
{
System.out.println("First object:");
System.out.println(new WithFinalFields());
System.out.println("First object:");
System.out.println(new WithFinalFields());
}
}
class SelfCounter{
private static int count;
private int id=count++;
public String toString()
{
return "self counter"+id;
}
}
class WithFinalFields
{
final SelfCounter selfCounter=new SelfCounter();
static final SelfCounter scsf=new SelfCounter();
public String toString()
{
return "selfCounter="+selfCounter+"\nscsf="+scsf;
}
}
コードの出力は次のとおりです。
First object:
selfCounter=self counter1
scsf=self counter0
First object:
selfCounter=self counter2
scsf=self counter0
scsf インスタンスは最終的な静的フィールドであると宣言されているため、両方の実行で常に 0 に割り当てられた id を取得する理由を理解できました。私を混乱させるのは、「selfCounter」オブジェクトの ID がそれぞれ 1 と 2 に割り当てられる理由です。別の静的インスタンス変数「count」に基づいて ID の計算がどのように実行されるかについて、少し行き詰まっています。
ご指導ありがとうございます。